RunLoop(運行循環)-002-加載大圖

UI界面滑動視圖時會卡頓,分析卡頓的緣由數組

1.渲染圖片耗時!! -- 分段加載圖片!!oop

 每次Runloop循環,最多須要加載18張大圖  因此卡住了
atom

思路:spa

 每次Runloop循環,只渲染一張大圖!!server

 步驟:圖片

 1.監聽Runloop的循環!!內存

 2.將加載大圖的代碼!放在一個數組裏面!!rem

 3.每次Runloop循環,取出一個加載大圖的任務執行!!get

在建立UI滑動視圖以後調用: addRunloopObserverit

typedef void(^runloopBlock)(void);//Ref 引用

@property(nonatomic,strong)NSMutableArray * tasks;

 

#pragma mark - <CFRunloop>

-(void)addTasks:(runloopBlock)task{

    [self.tasks addObject:task];

    if (self.tasks.count > 18) {//Runloop 最大加載18張大圖

        [self.tasks removeObjectAtIndex:0];

    }

}

-(void)addRunloopObserver{

    //獲取Runloop

    CFRunLoopRef runloop = CFRunLoopGetCurrent();

    //定義一個context

    CFRunLoopObserverContext context = {

        0,

        (__bridge void *)(self),

        &CFRetain,

        &CFRelease,

        NULL

    };

    //定義觀察者

    static CFRunLoopObserverRef runloopObserver;

    runloopObserver = CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, YES, 0, &callBack, &context);

    //添加觀察者

    CFRunLoopAddObserver(runloop, runloopObserver, kCFRunLoopCommonModes);

    //C裏面 一旦creat new copy 有堆空間 須要本身手動釋放

    CFRelease(runloopObserver);

}

void  callBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info){

    //activity BeforeWaiting

    NSLog(@"%@",info);

    ViewController * vc = (__bridge ViewController *)info;

    if(vc.tasks.count == 0){

        return;

    }

    runloopBlock block = vc.tasks.firstObject;

    block();

    [vc.tasks removeObjectAtIndex:0];

}

使用

- (void)viewDidLoad {

    [super viewDidLoad];

    

    [NSTimer scheduledTimerWithTimeInterval:0.0001 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];

    _tasks = [NSMutableArray array];

    //setupUI

    [self addRunloopObserver];

}

-(void)timerMethod{

    //不幹任何事情!

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    //幹掉contentView上面的子控件!! 節約內存!!

    for (NSInteger i = 1; i <= 5; i++) {

        //幹掉contentView 上面的全部子控件!!

        [[cell.contentView viewWithTag:i] removeFromSuperview];

    }

    //添加文字

    [ViewController addlabel:cell indexPath:indexPath];

    //添加圖片

    [self addTasks:^{

        [ViewController addImage1With:cell];

    }];

    [self addTasks:^{

        [ViewController addImage2With:cell];

    }];

    [self addTasks:^{

        [ViewController addImage3With:cell];

    }];

    

    return cell;

}

相關文章
相關標籤/搜索