iOS开发iOS学习笔记首页投稿(暂停使用,暂停投稿)

IOS开发实用技巧(二)

2016-10-22  本文已影响596人  钟环

主要学习:
1 . RunLoop深入浅出;
2 . 预缓存思想;
3 . 第三方框架一句代码解决UITableView自动缓存行高;

1.RunLoop初步了解

2.RunLoop高级用法

3.demo案例一:

// 创建Observer  
  /*     
     第1个参数: 指定如何给observer分配存储空间     
     第2个参数: 需要监听的状态类型/ kCFRunLoopAllActivities监听所有状态     
     第3个参数: 是否每次都需要监听    
     第4个参数: 优先级     
     第5个参数: 监听到状态改变之后的回调   
  */
    CFRunLoopObserverRef  observer = CFRunLoopObserverCreateWithHandler(CFAllocatorGetDefault(), kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
/**
  ypedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
 kCFRunLoopEntry         = (1UL << 0), // 即将进入Loop
  kCFRunLoopBeforeTimers  = (1UL << 1), // 即将处理 Timer
  kCFRunLoopBeforeSources = (1UL << 2), // 即将处理 Source 
 kCFRunLoopBeforeWaiting = (1UL << 5), // 即将进入休眠  
  kCFRunLoopAfterWaiting  = (1UL << 6), // 刚从休眠中唤醒
  kCFRunLoopExit          = (1UL << 7), // 即将退出Loop     };
 */
    }
});
 // 给主线程的RunLoop添加一个观察者    
/* 第1个参数: 需要给哪个RunLoop添加观察者     
     第2个参数: 需要添加的Observer对象     
     第3个参数: 在哪种模式下可以可以监听     
*/
    CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopDefaultMode);
    // 释放对象
    CFRelease(observer);

4.消息循环即将进入休眠状态时,也就是要空闲时,进行一些后台的操作,这样某种程度上提高流畅度,比如动态缓存cell的行高.

下面的demo是多么的优雅.

    CFRunLoopRef runLoop = CFRunLoopGetCurrent();
    CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler    (kCFAllocatorDefault, kCFRunLoopBeforeWaiting, true, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity _) {
        // TODO here
    for (int i = 0;i<2 ;i++ ) {          
              NSLog(@"%d-->%@",i,[NSThread currentThread]);
          }
     });
    CFRunLoopAddObserver(runLoop, observer, kCFRunLoopDefaultMode);
//   CFRunLoopRemoveObserver(runLoop, observer, kCFRunLoopDefaultMode);
//   CFRelease(observer); // 注意释放,否则会造成内存泄露

注意:若要继续深入了解,需要深入Core Foundation框架中observer/timer/source模式.

5.如何用一句话解决缓存行高问题

pod search UITableView+FDTemplateLayoutCell
并导入UITableView+FDTemplateLayoutCell第三方库

#import "UITableView+FDTemplateLayoutCell.h"
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    return [tableView fd_heightForCellWithIdentifier:@"reuse identifer" configuration:^(id cell) {
        // Configure this cell with data, same as what you've done in "-tableView:cellForRowAtIndexPath:"
       
// Like:模型—数组—赋值

        // cell.entity = self.feedEntities[indexPath.row];
    }];
}

如果要debug调试: self.tableView.fd_debugLogEnabled = YES;
github 地址: https://github.com/forkingdog/UITableView-FDTemplateLayoutCell
天朝的讲解: http://blog.sunnyxx.com/2015/05/17/cell-height-calculation/

总结:学习利用RunLoop空闲时间执行预缓存任务
预缓存机制
利用RunLoop空闲时间执行预缓存任务,预缓存机制将在 UITableView 没有滑动的空闲时刻执行,计算和缓存那些还没有显示到屏幕中的 cell,整个缓存过程完全没有感知,这使得完整列表的高度计算既没有发生在加载时,又没有发生在滑动时,同时保证了加载速度和滑动流畅性.

上一篇下一篇

猜你喜欢

热点阅读