UI界面滑动视图时会卡顿,分析卡顿的原因:
1.渲染图片耗时!! -- 分段加载图片!!
每次Runloop循环,最多需要加载18张大图 所以卡住了
思路:
每次Runloop循环,只渲染一张大图!!
步骤:
1.监听Runloop的循环!!
2.将加载大图的代码!放在一个数组里面!!
3.每次Runloop循环,取出一个加载大图的任务执行!!
在创建UI滑动视图之后调用: addRunloopObserver
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;
}