美文网首页iOS基本功OC底层相关iOS 知识点
iOS-RunLoop在实际开发过程中的应用

iOS-RunLoop在实际开发过程中的应用

作者: 木子奕 | 来源:发表于2019-01-27 23:13 被阅读70次

    参考文章

    RunLoop的使用场景

    下面介绍一下,可以使用RunLoop的几个使用场景。

    1.保证线程的长时间存活

    在iOS开发过程中,有时候我们不希望一些花费时间比较长的操作阻塞主线程,导致界面卡顿,那么我们就会创建一个子线程,然后把这些花费时间比较长的操作放在子线程中来处理。可是当子线程中的任务执行完毕后,子线程就会被销毁掉。 怎么来验证上面这个结论呢?首先,我们创建一个HLThread类,继承自NSThread,然后重写dealloc 方法。

    @interface HLThread : NSThread
    ​
    @end
    ​
    @implementation HLThread
    ​
    - (void)dealloc
    {
      NSLog(@"%s",__func__);
    }
    ​
    @end
    

    然后,在控制器中用HLThread创建一个线程,执行一个任务,观察任务执行完毕后,线程是否被销毁。

    - (void)viewDidLoad {
      [super viewDidLoad];
    ​
      // 1.测试线程的销毁
      [self threadTest];
    }
    ​
    - (void)threadTest
    {
      HLThread *subThread = [[HLThread alloc] initWithTarget:self selector:@selector(subThreadOpetion) object:nil];
      [subThread start];
    }
    ​
    - (void)subThreadOpetion
    {
      @autoreleasepool {
          NSLog(@"%@----子线程任务开始",[NSThread currentThread]);
          [NSThread sleepForTimeInterval:3.0];
          NSLog(@"%@----子线程任务结束",[NSThread currentThread]);
      }
    }
    

    控制台输出的结果如下:

    2016-12-01 16:44:25.559 RunLoopDemo[4516:352041] <HLThread: 0x608000275680>{number = 4, name = (null)}----子线程任务开始
    2016-12-01 16:44:28.633 RunLoopDemo[4516:352041] <HLThread: 0x608000275680>{number = 4, name = (null)}----子线程任务结束
    2016-12-01 16:44:28.633 RunLoopDemo[4516:352041] -[HLThread dealloc]
    

    当子线程中的任务执行完毕后,线程就被立刻销毁了。如果程序中,需要经常在子线程中执行任务,频繁的创建和销毁线程,会造成资源的浪费。这时候我们就可以使用RunLoop来让该线程长时间存活而不被销毁。

    我们将上面的示例代码修改一下,修改后的代码过程为,创建一个子线程,当子线程启动后,启动runloop,点击视图,会在子线程中执行一个耗时3秒的任务(其实就是让线程睡眠3秒)。

    修改后的代码如下:

    @implementation ViewController
    ​
    - (void)viewDidLoad {
      [super viewDidLoad];
    ​
      // 1.测试线程的销毁
      [self threadTest];
    }
    ​
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
      [self performSelector:@selector(subThreadOpetion) onThread:self.subThread withObject:nil waitUntilDone:NO];
    }
    ​
    - (void)threadTest
    {
      HLThread *subThread = [[HLThread alloc] initWithTarget:self selector:@selector(subThreadEntryPoint) object:nil];
      [subThread setName:@"HLThread"];
      [subThread start];
      self.subThread = subThread;
    }
    ​
    /**
    子线程启动后,启动runloop
    */
    - (void)subThreadEntryPoint
    {
      @autoreleasepool {
          NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
          //如果注释了下面这一行,子线程中的任务并不能正常执行
          [runLoop addPort:[NSMachPort port] forMode:NSRunLoopCommonModes];
          NSLog(@"启动RunLoop前--%@",runLoop.currentMode);
          [runLoop run];
      }
    }
    ​
    /**
    子线程任务
    */
    - (void)subThreadOpetion
    {
      NSLog(@"启动RunLoop后--%@",[NSRunLoop currentRunLoop].currentMode);
      NSLog(@"%@----子线程任务开始",[NSThread currentThread]);
      [NSThread sleepForTimeInterval:3.0];
      NSLog(@"%@----子线程任务结束",[NSThread currentThread]);
    }
    ​
    @end
    

    先看控制台输出结果:

    2016-12-01 17:22:44.396 RunLoopDemo[4733:369202] 启动RunLoop前--(null)
    2016-12-01 17:22:49.285 RunLoopDemo[4733:369202] 启动RunLoop后--kCFRunLoopDefaultMode
    2016-12-01 17:22:49.285 RunLoopDemo[4733:369202] <HLThread: 0x60000027cb40>{number = 4, name = HLThread}----子线程任务开始
    2016-12-01 17:22:52.359 RunLoopDemo[4733:369202] <HLThread: 0x60000027cb40>{number = 4, name = HLThread}----子线程任务结束
    2016-12-01 17:22:55.244 RunLoopDemo[4733:369202] 启动RunLoop后--kCFRunLoopDefaultMode
    2016-12-01 17:22:55.245 RunLoopDemo[4733:369202] <HLThread: 0x60000027cb40>{number = 4, name = HLThread}----子线程任务开始
    2016-12-01 17:22:58.319 RunLoopDemo[4733:369202] <HLThread: 0x60000027cb40>{number = 4, name = HLThread}----子线程任务结束
    

    有几点需要注意: 1.获取RunLoop只能使用 [NSRunLoop currentRunLoop] 或 [NSRunLoop mainRunLoop]; 2.即使RunLoop开始运行,如果RunLoop 中的 modes为空,或者要执行的mode里没有item,那么RunLoop会直接在当前loop中返回,并进入睡眠状态。 3.自己创建的Thread中的任务是在kCFRunLoopDefaultMode这个mode中执行的。 4.在子线程创建好后,最好所有的任务都放在AutoreleasePool中。

    注意点一解释 RunLoop官方文档中的第二段中就已经说明了,我们的应用程序并不需要自己创建RunLoop,而是要在合适的时间启动runloop。 CF框架源码中有CFRunLoopGetCurrent(void)CFRunLoopGetMain(void),查看源码可知,这两个API中,都是先从全局字典中取,如果没有与该线程对应的RunLoop,那么就会帮我们创建一个RunLoop(创建RunLoop的过程在函数_CFRunLoopGet0(pthread_tt)中)。

    注意点二解释 这一点,可以将示例代码中的[runLoop addPort:[NSMachPort port]forMode:NSRunLoopCommonModes];,可以看到注释掉后,无论我们如何点击视图,控制台都不会有任何的输出,那是因为mode中并没有item任务。经过NSRunLoop封装后,只可以往mode中添加两类item任务:NSPort(对应的是source)、NSTimer,如果使用CFRunLoopRef,则可以使用C语言API,往mode中添加source、timer、observer。 如果不添加 [runLoop addPort:[NSMachPort port]forMode:NSRunLoopCommonModes];,我们把runloop的信息输出,可以看到:

    727768-320115694bf8d18a.png.jpeg

    如果我们添加上[runLoop addPort:[NSMachPort port]forMode:NSRunLoopCommonModes];,再把RunLoop的信息输出,可以看到:

    727768-5f28202d76ac5997.png.jpeg

    注意点三解释 怎么确认自己创建的子线程上的任务是在kCFRunLoopDefaultMode这个mode中执行的呢? 我们只需要在执行任务的时候,打印出该RunLoop的currentMode即可。 因为RunLoop执行任务是会在mode间切换,只执行该mode上的任务,每次切换到某个mode时,currentMode就会更新。源码请下载:CF框架源码 CFRunLoopRun()方法中会调用CFRunLoopRunSpecific()方法,而CFRunLoopRunSpecific()方法中有这么两行关键代码:

    CFRunLoopModeRef currentMode = __CFRunLoopFindMode(rl, modeName, false);
    ......这中间还有好多逻辑代码
    CFRunLoopModeRef previousMode = rl->_currentMode;
    rl->_currentMode = currentMode;
    ...... 这中间也有一堆的逻辑
    rl->_currentMode = previousMode;
    

    我测试后,控制台输出的是:

    2016-12-02 11:09:47.909 RunLoopDemo[5479:442560] 启动RunLoop后--kCFRunLoopDefaultMode
    2016-12-02 11:09:47.910 RunLoopDemo[5479:442560] <HLThread: 0x608000270a80>{number = 4, name = HLThread}----子线程任务开始
    2016-12-02 11:09:50.984 RunLoopDemo[5479:442560] <HLThread: 0x608000270a80>{number = 4, name = HLThread}----子线程任务结束
    

    注意点四解释 关于AutoReleasePool的官方文档中有提到:

    If you spawn a secondary thread.You must create your own autorelease pool block as soon as the thread begins executing; otherwise, your application will leak objects. (See Autorelease Pool Blocks and Threads for details.)
    Each thread in a Cocoa application maintains its own stack of autorelease pool blocks. If you are writing a Foundation-only program or if you detach a thread, you need to create your own autorelease pool block.
    If your application or thread is long-lived and potentially generates a lot of autoreleased objects, you should use autorelease pool blocks (like AppKit and UIKit do on the main thread); otherwise, autoreleased objects accumulate and your memory footprint grows.
    If your detached thread does not make Cocoa calls, you do not need to use an autorelease pool block.

    AFNetworking中的RunLoop案例

    在AFNetworking2.6.3之前的版本,使用的还是NSURLConnection,可以在AFURLConnectionOperation中找到使用RunLoop的源码:

    + (void)networkRequestThreadEntryPoint:(id)__unused object {
      @autoreleasepool {
          [[NSThread currentThread] setName:@"AFNetworking"];
          NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
          [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
          [runLoop run];
      }
    }
    ​
    + (NSThread *)networkRequestThread {
      static NSThread *_networkRequestThread = nil;
      static dispatch_once_t oncePredicate;
      dispatch_once(&oncePredicate, ^{
          _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
          [_networkRequestThread start];
      });
      return _networkRequestThread;
    }
    

    AFNetworking都是通过调用 [NSObject performSelector:onThread:..] 将这个任务扔到了后台线程的RunLoop 中。

    - (void)start {
      [self.lock lock];
      if ([self isCancelled]) {
          [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
      } else if ([self isReady]) {
          self.state = AFOperationExecutingState;
          [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
      }
      [self.lock unlock];
    }
    

    我们在使用NSURLConnection或者NSStream时,也需要考虑到RunLoop问题,因为默认情况下这两个类的对象生成后,都是在当前线程的NSDefaultRunLoopMode模式下执行任务。如果是在主线程,那么就会出现滚动ScrollView以及其子视图时,主线程的RunLoop切换到UITrackingRunLoopMode模式,那么NSURLConnection或者NSStream的回调就无法执行了。

    要解决这个问题,有两种方式: 第一种方式是创建出NSURLConnection对象或者NSStream对象后,再调用 -(void)scheduleInRunLoop:(NSRunLoop *)aRunLoopforMode:(NSRunLoopMode)mode,设置RunLoopMode即可。需要注意的是NSURLConnection必须使用其初始化构造方法-(nullable instancetype)initWithRequest:(NSURLRequest *)requestdelegate:(nullable id)delegatestartImmediately:(BOOL)startImmediately来创建对象,设置Mode才会起作用。

    第二种方式,就是所有的任务都在子线程中执行,并保证子线程的RunLoop正常运行即可(即上面AFNetworking的做法,因为主线程的RunLoop切换到UITrackingRunLoopMode,并不影响其他线程执行哪个mode中的任务,计算机CPU是在每一个时间片切换到不同的线程去跑一会,呈现出的多线程效果)。

    二、RunLoop如何保证NSTimer在视图滑动时,依然能正常运转

    使用场景

    1.我们经常会在应用中看到tableView 的header上是一个横向ScrollView,一般我们使用NSTimer,每隔几秒切换一张图片。可是当我们滑动tableView的时候,顶部的scollView并不会切换图片,这可怎么办呢? 2.界面上除了有tableView,还有显示倒计时的Label,当我们在滑动tableView时,倒计时就停止了,这又该怎么办呢?

    场景中的代码实现

    我们的定时器Timer是怎么写的呢? 一般的做法是,在主线程(可能是某控制器的viewDidLoad方法)中,创建Timer。 可能会有两种写法,但是都有上面的问题,下面先看下Timer的两种写法:

    // 第一种写法
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [timer fire];
    // 第二种写法
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
    

    上面的两种写法其实是等价的。第二种写法,默认也是将timer添加到NSDefaultRunLoopMode下的,并且会自动fire。。 要验证这一结论,我们只需要在timerUpdate方法中,将当前runLoop的currentMode打印出来即可。

    - (void)timerUpdate
    {
      NSLog(@"当前线程:%@",[NSThread currentThread]);
      NSLog(@"启动RunLoop后--%@",[NSRunLoop currentRunLoop].currentMode);
    //   NSLog(@"currentRunLoop:%@",[NSRunLoop currentRunLoop]);
      dispatch_async(dispatch_get_main_queue(), ^{
          self.count ++;
          NSString *timerText = [NSString stringWithFormat:@"计时器:%ld",self.count];
          self.timerLabel.text = timerText;
      });
    }
    // 控制台输出结果:
    2016-12-02 15:33:57.829 RunLoopDemo02[6698:541533] 当前线程:<NSThread: 0x600000065500>{number = 1, name = main}
    2016-12-02 15:33:57.829 RunLoopDemo02[6698:541533] 启动RunLoop后--kCFRunLoopDefaultMode
    

    然后,我们在滑动tableView的时候timerUpdate方法,并不会调用。 ** 原因是啥呢?** 原因是当我们滑动scrollView时,主线程的RunLoop会切换到UITrackingRunLoopMode这个Mode,执行的也是UITrackingRunLoopMode下的任务(Mode中的item),而timer是添加在NSDefaultRunLoopMode下的,所以timer任务并不会执行,只有当UITrackingRunLoopMode的任务执行完毕,runloop切换到NSDefaultRunLoopMode后,才会继续执行timer。

    ** 要如何解决这一问题呢?** 解决方法很简单,我们只需要在添加timer 时,将mode 设置为NSRunLoopCommonModes即可。

    - ( void)timerTest
    {
      // 第一种写法
      NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
      [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
      [timer fire];
      // 第二种写法,因为是固定添加到defaultMode中,就不要用了
    }
    

    RunLoop官方文档iPhonedevwiki中的CFRunLoop可以看出,NSRunLoopCommonModes并不是一种Mode,而是一种特殊的标记,关联的有一个set,官方文档说:For Cocoa applications, this set includes the default, modal, andevent tracking modes bydefault.(默认包含NSDefaultRunLoopModeNSModalPanelRunLoopModeNSEventTrackingRunLoopMode) 添加到NSRunLoopCommonModes中的还没有执行的任务,会在mode切换时,再次添加到当前的mode中,这样就能保证不管当前runloop切换到哪一个mode,任务都能正常执行。并且被添加到NSRunLoopCommonModes中的任务会存储在runloop的commonModeItems中。

    其他一些关于timer的坑

    我们在子线程中使用timer,也可以解决上面的问题,但是需要注意的是把timer加入到当前runloop后,必须让runloop运行起来,否则timer仅执行一次。

    示例代码:

    //首先是创建一个子线程
    - (void)createThread
    {
      NSThread *subThread = [[NSThread alloc] initWithTarget:self selector:@selector(timerTest) object:nil];
      [subThread start];
      self.subThread = subThread;
    }
    ​
    // 创建timer,并添加到runloop的mode中
    - (void)timerTest
    {
      @autoreleasepool {
          NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
          NSLog(@"启动RunLoop前--%@",runLoop.currentMode);
          NSLog(@"currentRunLoop:%@",[NSRunLoop currentRunLoop]);
          // 第一种写法,改正前
      //   NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
      //   [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
      //   [timer fire];
          // 第二种写法
            [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
    ​
          [[NSRunLoop currentRunLoop] run];
      }
    }
    ​
    //更新label
    - (void)timerUpdate
    {
      NSLog(@"当前线程:%@",[NSThread currentThread]);
      NSLog(@"启动RunLoop后--%@",[NSRunLoop currentRunLoop].currentMode);
      NSLog(@"currentRunLoop:%@",[NSRunLoop currentRunLoop]);
      dispatch_async(dispatch_get_main_queue(), ^{
          self.count ++;
          NSString *timerText = [NSString stringWithFormat:@"计时器:%ld",self.count];
          self.timerLabel.text = timerText;
      });
    }
    

    添加timer 前的控制台输出:

    727768-468c6aecb685bcad-2.png

    添加timer后的控制台输出:

    727768-9ab1df48dcb01b95.png.jpeg

    从控制台输出可以看出,timer确实被添加到NSDefaultRunLoopMode中了。可是添加到子线程中的NSDefaultRunLoopMode里,无论如何滚动,timer都能够很正常的运转。这又是为啥呢?

    这就是多线程与runloop的关系了,每一个线程都有一个与之关联的RunLoop,而每一个RunLoop可能会有多个Mode。CPU会在多个线程间切换来执行任务,呈现出多个线程同时执行的效果。执行的任务其实就是RunLoop去各个Mode里执行各个item。因为RunLoop是独立的两个,相互不会影响,所以在子线程添加timer,滑动视图时,timer能正常运行。

    总结

    1、如果是在主线程中运行timer,想要timer在某界面有视图滚动时,依然能正常运转,那么将timer添加到RunLoop中时,就需要设置mode为NSRunLoopCommonModes。 2、如果是在子线程中运行timer,那么将timer添加到RunLoop中后,Mode设置为NSDefaultRunLoopModeNSRunLoopCommonModes均可,但是需要保证RunLoop在运行,且其中有任务。

    三、UITableView、UICollectionView等的滑动优化

    让UITableView、UICollectionView等延迟加载图片。下面就拿UITableView来举例说明: UITableView 的 cell 上显示网络图片,一般需要两步,第一步下载网络图片;第二步,将网络图片设置到UIImageView上。 为了不影响滑动,第一步,我们一般都是放在子线程中来做,这个不做赘述。 第二步,一般是回到主线程去设置。有了前两节文章关于Mode的切换,想必你已经知道怎么做了。 就是在为图片视图设置图片时,在主线程设置,并调用performSelector:withObject:afterDelay:inModes:方法。最后一个参数,仅设置一个NSDefaultRunLoopMode

    UIImage *downloadedImage = ....;
    [self.myImageView performSelector:@selector(setImage:) withObject:downloadedImage afterDelay:0 inModes:@[NSDefaultRunLoopMode]];
    

    当然,即使是读取沙盒或者bundle内的图片,我们也可以运用这一点来改善视图的滑动。但是如果UITableView上的图片都是默认图,似乎也不是很好,你需要自己来权衡了。

    有一个非常好的关于设置图片视图的图片,在RunLoop切换Mode时优化的例子:RunLoopWorkDistribution 先看一下界面布局:

    image

    一个Cell里有两个Label,和三个imageView,这里的图片是非常高清的(2034 ×1525),一个界面最多有18张图片。为了表现出卡顿的效果,我先自己实现了一下Cell,主要示例代码:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
      static NSString *identifier = @"cellId";
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
      if (cell == nil) {
          cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
      }
      for (NSInteger i = 1; i <= 5; i++) {
          [[cell.contentView viewWithTag:i] removeFromSuperview];
      }
    ​
      UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 300, 25)];
      label.backgroundColor = [UIColor clearColor];
      label.textColor = [UIColor redColor];
      label.text = [NSString stringWithFormat:@"%zd - Drawing index is top priority", indexPath.row];
      label.font = [UIFont boldSystemFontOfSize:13];
      label.tag = 1;
      [cell.contentView addSubview:label];
    ​
      UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(105, 20, 85, 85)];
      imageView.tag = 2;
      NSString *path = [[NSBundle mainBundle] pathForResource:@"spaceship" ofType:@"jpg"];
      UIImage *image = [UIImage imageWithContentsOfFile:path];
      imageView.contentMode = UIViewContentModeScaleAspectFit;
      imageView.image = image;
      NSLog(@"current:%@",[NSRunLoop currentRunLoop].currentMode);
      [cell.contentView addSubview:imageView];
    ​
      UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(200, 20, 85, 85)];
      imageView2.tag = 3;
      UIImage *image2 = [UIImage imageWithContentsOfFile:path];
      imageView2.contentMode = UIViewContentModeScaleAspectFit;
      imageView2.image = image2;
      [cell.contentView addSubview:imageView2];
    ​
      UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(5, 99, 300, 35)];
      label2.lineBreakMode = NSLineBreakByWordWrapping;
      label2.numberOfLines = 0;
      label2.backgroundColor = [UIColor clearColor];
      label2.textColor = [UIColor colorWithRed:0 green:100.f/255.f blue:0 alpha:1];
      label2.text = [NSString stringWithFormat:@"%zd - Drawing large image is low priority. Should be distributed into different run loop passes.", indexPath.row];
      label2.font = [UIFont boldSystemFontOfSize:13];
      label2.tag = 4;
    ​
      UIImageView *imageView3 = [[UIImageView alloc] initWithFrame:CGRectMake(5, 20, 85, 85)];
      imageView3.tag = 5;
      UIImage *image3 = [UIImage imageWithContentsOfFile:path];
      imageView3.contentMode = UIViewContentModeScaleAspectFit;
      imageView3.image = image3;
      [cell.contentView addSubview:label2];
      [cell.contentView addSubview:imageView3];
    ​
      return cell;
    }
    

    然后在滑动的时候,顺便打印出当前的runloopMode,打印结果是:

    2016-12-08 10:34:31.450 TestDemo[3202:1791817] current:UITrackingRunLoopMode
    2016-12-08 10:34:31.701 TestDemo[3202:1791817] current:UITrackingRunLoopMode
    2016-12-08 10:34:32.184 TestDemo[3202:1791817] current:UITrackingRunLoopMode
    2016-12-08 10:34:36.317 TestDemo[3202:1791817] current:UITrackingRunLoopMode
    2016-12-08 10:34:36.601 TestDemo[3202:1791817] current:UITrackingRunLoopMode
    2016-12-08 10:34:37.217 TestDemo[3202:1791817] current:UITrackingRunLoopMode
    

    可以看出,为imageView设置image,是在UITrackingRunLoopMode中进行的,如果图片很大,图片解压缩和渲染肯定会很耗时,那么卡顿就是必然的。

    查看实时帧率,我们可以在Xcode 中选择真机调试,然后 Product –>Profile–>Core Animation

    image 然后点击开始监测即可: image

    下面就是帧率:

    image

    这里就可以使用先使用上面的方式做一次改进。

    [imageView performSelector:@selector(setImage:) withObject:image afterDelay:0 inModes:@[NSDefaultRunLoopMode]];
    

    可以保证在滑动起来顺畅,可是停下来之后,渲染还未完成时,继续滑动就会变的卡顿。 在切换到NSDefaultRunLoopMode中,一个runloop循环要解压和渲染18张大图,耗时肯定超过50ms(1/60s)。 我们可以继续来优化,一次runloop循环,仅渲染一张大图片,分18次来渲染,这样每一次runloop耗时就比较短了,滑动起来就会非常顺畅。这也是RunLoopWorkDistribution中的做法。 简单描述一下这种做法: 首先创建一个单例,单例中定义了几个数组,用来存要在runloop循环中执行的任务,然后为主线程的runloop添加一个CFRunLoopObserver,当主线程在NSDefaultRunLoopMode中执行完任务,即将睡眠前,执行一个单例中保存的一次图片渲染任务。关键代码看DWURunLoopWorkDistribution类即可。

    一点UITableView滑动性能优化扩展

    影响UITableView的滑动,有哪些因素呢? 关于这一点,人眼能识别的帧率是60左右,这也就是为什么,电脑屏幕的最佳帧率是60Hz。 屏幕一秒钟会刷新60次(屏幕在一秒钟会重新渲染60次),那么每次刷新界面之间的处理时间,就是1/60,也就是1/60秒。也就是说,所有会导致计算、渲染耗时的操作都会影响UITableView的流畅。下面举例说明:

    1.在主线程中做耗时操作 耗时操作,包括从网络下载、从网络加载、从本地数据库读取数据、从本地文件中读取大量数据、往本地文件中写入数据等。(这一点,相信大家都知道,要尽量避免在主线程中执行,一般都是创建一个子线程来执行,然后再回到主线程)

    2.动态计算UITableViewCell的高度,时间过久 在iOS7之前,每一个Cell的高度,只会计算一次,后面再次滑到这个Cell这里,都会读取缓存的高度,也即高度计算的代理方法不会再执行。但是到了iOS8,不会再缓存Cell的高度了,也就是说每次滑到某个Cell,代理方法都会执行一次,重新计算这个Cell的高度(iOS9以后没测试过)。 所以,如果计算Cell高度的这个过程过于复杂,或者某个计算使用的算法耗时很长,可能会导致计算时间大于1/60,那么必然导致界面的卡顿,或不流畅。

    关于这一点,我以前的做法是在Cell中定义一个public方法,用来计算Cell高度,然后计算完高度后,将高度存储在Cell对应的Model中(Model里定义一个属性来存高度),然后在渲染Cell时,我们依然需要动态计算各个子视图的高度。(可能是没用什么太过复杂的计算或算法,时间都很短滑动也顺畅)

    其实,更优的做法是:再定义一个ModelFrame对象,在子线程请求服务器接口返回后,转换为对象的同时,也把各个子视图的frame计算好,存在ModelFrame中,ModelFrame和 Model 合并成一个Model存储到数组中。这样在为Cell各个子控件赋值时,仅仅是取值、赋值,在计算Cell高度时,也仅仅是加法运算。

    3.界面中背景色透明的视图过多 为什么界面中背景色透明的视图过多会影响UITableView的流畅?

    很多文章中都提到,可以使用模拟器—>Debug—>Color BlendedLayers来检测透明背景色,把透明背景色改为与父视图背景色一样的颜色,这样来提高渲染速度。

    image

    简单说明一下,就是屏幕上显示的所有东西,都是通过一个个像素点呈现出来的。而每一个像素点都是通过三原色(红、绿、蓝)组合呈现出不同的颜色,最终才是我们看到的手机屏幕上的内容。在iPhone5 的液晶显示器上有1,136×640=727,040个像素,因此有2,181,120个颜色单元。在15寸视网膜屏的 MacBook Pro上,这一数字达到15.5百万以上。所有的图形堆栈一起工作以确保每次正确的显示。当你滚动整个屏幕的时候,数以百万计的颜色单元必须以每秒60次的速度刷新,这是一个很大的工作量。

    每一个像素点的颜色计算是这样的: R = S + D * (1 - Sa) 结果的颜色 是子视图这个像素点的颜色 + 父视图这个像素点的颜色 * (1 - 子视图的透明度) 当然,如果有两个兄弟视图叠加,那么上面的中文解释可能并不贴切,只是为了更容易理解。

    如果两个兄弟视图重合,计算的是重合区域的像素点: 结果的颜色 是 上面的视图这个像素点的颜色 + 下面这个视图该像素点的颜色 * (1 - 上面视图的透明度)

    只有当透明度为1时,上面的公式变为R = S,就简单的多了。否则的话,就非常复杂了。 每一个像素点是由三原色组成,例如父视图的颜色和透明度是(Pr,Pg,Pb,Pa),子视图的颜色颜色和透明度是(Sr,Sg,Sb,Sa),那么我们计算这个重合区域某像素点的颜色,需要先分别计算出红、绿、蓝。 Rr = Sr + Pr * (1 - Sa), Rg = Sg + Pg * (1 - Sa), Rb = Sb + Pb * (1 - Sa)。 如果父视图的透明度,即Pa = 1,那么这个像素的颜色就是(Rr,Rg,Rb)。 但是,如果父视图的透明Pa 不等 1,那么我们需要将这个结果颜色当做一个整体作为子视图的颜色,再去与父视图组合计算颜色,如此递推。

    所以设置不透明时,可以为GPU节省大量的工作,减少大量的消耗。

    更加详细的说明,可以看绘制像素到屏幕上这篇文章,这是一篇关于绘制像素的非常棒

    使用TableView时出现的问题:

    平时开发中绘制 tableView 时,我们使用的 cell 可能包含很多业务逻辑,比如加载网络图片、绘制内容等等。如果我们不进行优化的话,在绘制cell 时这些任务将同时争夺系统资源,最直接的后果就是页面出现卡顿,更严重的则会 crash。 我通过在 cell 上加载大的图片(找的系统的壁纸,大小10M左右)并改变其大小来模拟 cell 的复杂业务逻辑。

    cell 的绘制方法中实现如下:

    CGFloat width = (self.view.bounds.size.width-4*kBorder_W) /3;
    ​
    UIImageView *img1 = [[UIImageView alloc] initWithFrame:CGRectMake(kBorder_W,
                                                                    kBorder_W,
                                                                    width,
                                                                    kCell_H-kBorder_W)];
    img1.image = [UIImage imageNamed:@"Blue Pond.jpg"];
    [cell addSubview:img1];
    UIImageView *img2 = [[UIImageView alloc] initWithFrame:CGRectMake(width+2*kBorder_W,
                                                                    kBorder_W,
                                                                    width,
                                                                    kCell_H-kBorder_W)];
    img2.image = [UIImage imageNamed:@"El Capitan 2.jpg"];
    [cell addSubview:img2];
    UIImageView *img3 = [[UIImageView alloc] initWithFrame:CGRectMake(2*width+3*kBorder_W,
                                                                    kBorder_W,
                                                                    width,
                                                                    kCell_H-kBorder_W)];
    img3.image = [UIImage imageNamed:@"El Capitan.jpg"];
    [cell addSubview:img3];
    

    tableView 在绘制 cell 的时候同时处理这么多资源,会导致页面滑动不流畅等问题。此处只是模拟,可能效果不明显,但这都不是重点~

    微信对cell 的优化方案是当监听到列表滚动时,停止 cell 上的动画等方式,来提升用户体验。

    Q:那么问题来了,这个监听是怎么做到的呢?

    • 一种是通过 scrollViewdelegate 方法;

    • 另一种就是通过监听 runLoop

    如果有其他方案,欢迎告知~

    二、下面就分享下通过监听RunLoop来优化TableView:

    步骤如下:

    (1).获取当前主线程的 runloop

    CFRunLoopRef runloop = CFRunLoopGetCurrent();
    

    (2).创建观察者 CFRunLoopObserverRef , 来监听 runloop

    • 创建观察者用到的核心函数就是 CFRunLoopObserverCreate
     // allocator:该参数为对象内存分配器,一般使用默认的分配器kCFAllocatorDefault。
    // activities:要监听runloop的状态
    /*typedef 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
    kCFRunLoopAllActivities = 0x0FFFFFFFU // 所有事件 };*/
    // repeats:是否重复监听
    // order:观察者优先级,当Run Loop中有多个观察者监听同一个运行状态时,根据该优先级判断,0为最高优先级别。
    // callout:观察者的回调函数,在Core Foundation框架中用CFRunLoopObserverCallBack重定义了回调函数的闭包。
    // context:观察者的上下文。
    CF_EXPORT CFRunLoopObserverRef CFRunLoopObserverCreate(CFAllocatorRef allocator, CFOptionFlags activities, Boolean repeats, CFIndex order, CFRunLoopObserverCallBack callout, CFRunLoopObserverContext *context);
    
    a).创建观察者
    // 1.定义上下文
    CFRunLoopObserverContext context = {
      0,
      (__bridge void *)(self),
      &CFRetain,
      &CFRelease,
      NULL
    };
    // 2.定义观察者
    static CFRunLoopObserverRef defaultModeObserver;
    // 3.创建观察者
    defaultModeObserver = CFRunLoopObserverCreate(kCFAllocatorDefault,
                                                kCFRunLoopBeforeWaiting,
                                                YES,
                                                0,
                                                &callBack,
                                                &context);
    // 4.给当前runloop添加观察者
    // kCFRunLoopDefaultMode: App的默认 Mode,通常主线程是在这个 Mode 下运行的。
    // UITrackingRunLoopMode: 界面跟踪 Mode,用于 ScrollView 追踪触摸滑动,保证界面滑动时不受其他 Mode 影响。
    // UIInitializationRunLoopMode: 在刚启动 App 时进入的第一个 Mode,启动完成后就不再使用。
    // GSEventReceiveRunLoopMode: 接受系统事件的内部 Mode,通常用不到。
    // kCFRunLoopCommonModes: 这是一个占位的 Mode,没有实际作用。
    CFRunLoopAddObserver(runloop, defaultModeObserver, kCFRunLoopCommonModes);
    // 5.内存管理
    CFRelease(defaultModeObserver);
    
    b).实现 callBack 函数,只要检测到对应的runloop状态,该函数就会得到响应。
    static void callBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
    
      ViewController *vc = (__bridge ViewController *)info;
    
      //无任务 退出
      if (vc.tasksArr.count == 0) return;
    
      //从数组中取出任务
      runloopBlock block = [vc.tasksArr firstObject];
    
      //执行任务
      if (block) {
          block();
      }
    
      //执行完任务之后移除任务
      [vc.tasksArr removeObjectAtIndex:0];
    
    }
    
    c).从上面的函数实现中我们看到了block、arr等对象,下面解析下:
    • 使用 Array 来存储需要执行的任务;
    - (NSMutableArray *)tasksArr {
        if (!_tasksArr) {
            _tasksArr = [NSMutableArray array];
        }
        return _tasksArr;
    }
    
    • 定义参数 maxTaskCount 来表示最大任务数,优化项目;

      //最大任务数@property (nonatomic, assign) NSUInteger maxTaskCount;...// 当超出最大任务数时,以前的老任务将从数组中移除self.maxTaskCount = 50;

    • 使用 block代码块 来包装一个个将要执行的任务,便于 callBack 函数中分开执行任务,减少同时执行对系统资源的消耗。

      //1. 定义一个任务blocktypedef void(^runloopBlock)();

      //2. 定义一个添加任务的方法,将任务装在数组中

    // 添加任务
    - (void)addTasks:(runloopBlock)task {
    //    NSLog(@"%d",_maxTaskCount);
    //     保存新任务
        [self.tasksArr addObject:task];
        // 如果超出最大任务数 丢弃之前的任务
        if (self.tasksArr.count > _maxTaskCount) {
            [self.tasksArr removeObjectAtIndex:0];
        }
    }
    
    //3\. 将任务添加到代码块中
    
        // 耗时操作可以放在任务中
        [self addTasks:^{
            UIImageView *img1 = [[UIImageView alloc] initWithFrame:CGRectMake(kBorder_W,
                                                                              kBorder_W,
                                                                              width,
                                                                              kCell_H-kBorder_W)];
            img1.image = [UIImage imageNamed:@"Blue Pond.jpg"];
            [cell addSubview:img1];
            CFRunLoopWakeUp(CFRunLoopGetCurrent());
        }];
        [self addTasks:^{
            UIImageView *img2 = [[UIImageView alloc] initWithFrame:CGRectMake(width+2*kBorder_W,
                                                                              kBorder_W,
                                                                              width,
                                                                              kCell_H-kBorder_W)];
            img2.image = [UIImage imageNamed:@"El Capitan 2.jpg"];
            [cell addSubview:img2];
            CFRunLoopWakeUp(CFRunLoopGetCurrent());
        }];
        [self addTasks:^{
            UIImageView *img3 = [[UIImageView alloc] initWithFrame:CGRectMake(2*width+3*kBorder_W,
                                                                              kBorder_W,
                                                                              width,
                                                                              kCell_H-kBorder_W)];
            img3.image = [UIImage imageNamed:@"El Capitan.jpg"];
            [cell addSubview:img3];
            CFRunLoopWakeUp(CFRunLoopGetCurrent());
        }];
    

    (3).使 runloop 不进入休眠状态。

    Q:按照上面步骤实现的情况下:我有500行的cell,为什么才显示这么一点点呢?
    3265534-c18a92fbb80f6e7c.png
    A:runloop 在加载完 cell 时没有其他事情做了,为了节省资源消耗,就进入了休眠状态,等待有任务时再次被唤醒。在我们观察者的

    callBack 函数中任务被一个个取出执行,还没有执行完,runloop 就切换状态了(休眠了), callBack函数不再响应。导致出现上面的情况。

    解决方法:
    //创建定时器 (保证runloop回调函数一直在执行)
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self
                                                            selector:@selector(notDoSomething)];
    [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    
    - (void)notDoSomething {
      // 不做事情,就是为了让 callBack() 函数一直相应
    }
    
    3265534-45f8cc797ee8d2c4.gif

    参考资料

    关于今天要介绍的使用RunLoop 监测主线程卡顿的资料如下:

    原理

    官方文档说明了RunLoop的执行顺序:

    1\. Notify observers that the run loop has been entered.
    2\. Notify observers that any ready timers are about to fire.
    3\. Notify observers that any input sources that are not port based are about to fire.
    4\. Fire any non-port-based input sources that are ready to fire.
    5\. If a port-based input source is ready and waiting to fire, process the event immediately. Go to step 9.
    6\. Notify observers that the thread is about to sleep.
    7\. Put the thread to sleep until one of the following events occurs:
    * An event arrives for a port-based input source.
    * A timer fires.
    * The timeout value set for the run loop expires.
    * The run loop is explicitly woken up.
    8\. Notify observers that the thread just woke up.
    9\. Process the pending event.
    * If a user-defined timer fired, process the timer event and restart the loop. Go to step 2.
    * If an input source fired, deliver the event.
    * If the run loop was explicitly woken up but has not yet timed out, restart the loop. Go to step 2.
    10\. Notify observers that the run loop has exited.
    

    用伪代码来实现就是这样的:

    {
      /// 1\. 通知Observers,即将进入RunLoop
      /// 此处有Observer会创建AutoreleasePool: _objc_autoreleasePoolPush();
      __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(kCFRunLoopEntry);
      do {
    ​
          /// 2\. 通知 Observers: 即将触发 Timer 回调。
          __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(kCFRunLoopBeforeTimers);
          /// 3\. 通知 Observers: 即将触发 Source (非基于port的,Source0) 回调。
          __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(kCFRunLoopBeforeSources);
          __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__(block);
    ​
          /// 4\. 触发 Source0 (非基于port的) 回调。
          __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__(source0);
          __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__(block);
    ​
          /// 6\. 通知Observers,即将进入休眠
          /// 此处有Observer释放并新建AutoreleasePool: _objc_autoreleasePoolPop(); _objc_autoreleasePoolPush();
          __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(kCFRunLoopBeforeWaiting);
    ​
          /// 7\. sleep to wait msg.
          mach_msg() -> mach_msg_trap();
    
        /// 8\. 通知Observers,线程被唤醒
          __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(kCFRunLoopAfterWaiting);
    ​
          /// 9\. 如果是被Timer唤醒的,回调Timer
          __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__(timer);
    ​
          /// 9\. 如果是被dispatch唤醒的,执行所有调用 dispatch_async 等方法放入main queue 的 block
          __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__(dispatched_block);
    ​
          /// 9\. 如果如果Runloop是被 Source1 (基于port的) 的事件唤醒了,处理这个事件
          __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__(source1);
    
     } while (...);
    ​
      /// 10\. 通知Observers,即将退出RunLoop
      /// 此处有Observer释放AutoreleasePool: _objc_autoreleasePoolPop();
      __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(kCFRunLoopExit);
    }
    

    主线程的RunLoop是在应用启动时自动开启的,也没有超时时间,所以正常情况下,主线程的RunLoop 只会在 2—9 之间无限循环下去。 那么,我们只需要在主线程的RunLoop中添加一个observer,检测从 kCFRunLoopBeforeSourceskCFRunLoopBeforeWaiting 花费的时间是否过长。如果花费的时间大于某一个阙值,我们就认为有卡顿,并把当前的线程堆栈转储到文件中,并在以后某个合适的时间,将卡顿信息文件上传到服务器。

    实现步骤

    在看了上面的两个监测卡顿的示例Demo后,我按照上面讲述的思路写了一个Demo,应该更容易理解吧。 第一步,创建一个子线程,在线程启动时,启动其RunLoop。

    + (instancetype)shareMonitor
    {
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
          instance = [[[self class] alloc] init];
          instance.monitorThread = [[NSThread alloc] initWithTarget:self selector:@selector(monitorThreadEntryPoint) object:nil];
          [instance.monitorThread start];
      });
    ​
      return instance;
    }
    ​
    + (void)monitorThreadEntryPoint
    {
      @autoreleasepool {
          [[NSThread currentThread] setName:@"FluencyMonitor"];
          NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
          [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
          [runLoop run];
      }
    }
    

    第二步,在开始监测时,往主线程的RunLoop中添加一个observer,并往子线程中添加一个定时器,每0.5秒检测一次耗时的时长。

    - (void)start
    {
      if (_observer) {
          return;
      }
    ​
      // 1.创建observer
      CFRunLoopObserverContext context = {0,(__bridge void*)self, NULL, NULL, NULL};
      _observer = CFRunLoopObserverCreate(kCFAllocatorDefault,
                                                kCFRunLoopAllActivities,
                                                YES,
                                                0,
                                                &runLoopObserverCallBack,
                                                &context);
      // 2.将observer添加到主线程的RunLoop中
      CFRunLoopAddObserver(CFRunLoopGetMain(), _observer, kCFRunLoopCommonModes);
    ​
      // 3.创建一个timer,并添加到子线程的RunLoop中
      [self performSelector:@selector(addTimerToMonitorThread) onThread:self.monitorThread withObject:nil waitUntilDone:NO modes:@[NSRunLoopCommonModes]];
    }
    ​
    - (void)addTimerToMonitorThread
    {
      if (_timer) {
          return;
      }
      // 创建一个timer
      CFRunLoopRef currentRunLoop = CFRunLoopGetCurrent();
      CFRunLoopTimerContext context = {0, (__bridge void*)self, NULL, NULL, NULL};
      _timer = CFRunLoopTimerCreate(kCFAllocatorDefault, 0.1, 0.01, 0, 0,
                                                      &runLoopTimerCallBack, &context);
      // 添加到子线程的RunLoop中
      CFRunLoopAddTimer(currentRunLoop, _timer, kCFRunLoopCommonModes);
    }
    

    第三步,补充观察者回调处理

    static void runLoopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info){
      FluencyMonitor *monitor = (__bridge FluencyMonitor*)info;
      NSLog(@"MainRunLoop---%@",[NSThread currentThread]);
      switch (activity) {
          case kCFRunLoopEntry:
              NSLog(@"kCFRunLoopEntry");
              break;
          case kCFRunLoopBeforeTimers:
              NSLog(@"kCFRunLoopBeforeTimers");
              break;
          case kCFRunLoopBeforeSources:
              NSLog(@"kCFRunLoopBeforeSources");
              monitor.startDate = [NSDate date];
              monitor.excuting = YES;
              break;
          case kCFRunLoopBeforeWaiting:
              NSLog(@"kCFRunLoopBeforeWaiting");
              monitor.excuting = NO;
              break;
          case kCFRunLoopAfterWaiting:
              NSLog(@"kCFRunLoopAfterWaiting");
              break;
          case kCFRunLoopExit:
              NSLog(@"kCFRunLoopExit");
              break;
          default:
              break;
      }
    }
    

    从打印信息来看,RunLoop进入睡眠状态的时间可能会非常短,有时候只有1毫秒,有时候甚至1毫秒都不到,静止不动时,则会长时间进入睡觉状态。

    因为主线程中的block、交互事件、以及其他任务都是在kCFRunLoopBeforeSourceskCFRunLoopBeforeWaiting 之前执行,所以我在即将开始执行Sources时,记录一下时间,并把正在执行任务的标记置为YES,将要进入睡眠状态时,将正在执行任务的标记置为NO。

    第四步,补充timer 的回调处理

    static void runLoopTimerCallBack(CFRunLoopTimerRef timer, void *info)
    {
      FluencyMonitor *monitor = (__bridge FluencyMonitor*)info;
      if (!monitor.excuting) {
          return;
      }
    ​
      // 如果主线程正在执行任务,并且这一次loop 执行到 现在还没执行完,那就需要计算时间差
      NSTimeInterval excuteTime = [[NSDate date] timeIntervalSinceDate:monitor.startDate];
      NSLog(@"定时器---%@",[NSThread currentThread]);
      NSLog(@"主线程执行了---%f秒",excuteTime);
    ​
      if (excuteTime >= 0.01) {
          NSLog(@"线程卡顿了%f秒",excuteTime);
          [monitor handleStackInfo];
      }
    }
    

    timer 每 0.01秒执行一次,如果当前正在执行任务的状态为YES,并且从开始执行到现在的时间大于阙值,则把堆栈信息保存下来,便于后面处理。 为了能够捕获到堆栈信息,我把timer的间隔调的很小(0.01),而评定为卡顿的阙值也调的很小(0.01)。实际使用时这两个值应该是比较大,timer间隔为1s,卡顿阙值为2s即可。

    2016-12-15 08:56:39.921 RunLoopDemo03[957:16300] lag happen, detail below: 
    Incident Identifier: 68BAB24C-3224-46C8-89BF-F9AABA2E3530
    CrashReporter Key:   TODO
    Hardware Model:     x86_64
    Process:         RunLoopDemo03 [957]
    Path:           /Users/harvey/Library/Developer/CoreSimulator/Devices/6ED39DBB-9F69-4ACB-9CE3-E6EB56BBFECE/data/Containers/Bundle/Application/5A94DEFE-4E2E-4D23-9F69-7B1954B2C960/RunLoopDemo03.app/RunLoopDemo03
    Identifier:     com.Haley.RunLoopDemo03
    Version:         1.0 (1)
    Code Type:       X86-64
    Parent Process: debugserver [958]
    ​
    Date/Time:       2016-12-15 00:56:38 +0000
    OS Version:     Mac OS X 10.1 (16A323)
    Report Version: 104
    ​
    Exception Type: SIGTRAP
    Exception Codes: TRAP_TRACE at 0x1063da728
    Crashed Thread: 4
    ​
    Thread 0:
    0   libsystem_kernel.dylib             0x000000010a14341a mach_msg_trap + 10
    1   CoreFoundation                     0x0000000106f1e7b4 __CFRunLoopServiceMachPort + 212
    2   CoreFoundation                     0x0000000106f1dc31 __CFRunLoopRun + 1345
    3   CoreFoundation                     0x0000000106f1d494 CFRunLoopRunSpecific + 420
    4   GraphicsServices                   0x000000010ad8aa6f GSEventRunModal + 161
    5   UIKit                               0x00000001073b7964 UIApplicationMain + 159
    6   RunLoopDemo03                       0x00000001063dbf8f main + 111
    7   libdyld.dylib                       0x0000000109d7468d start + 1
    ​
    Thread 1:
    0   libsystem_kernel.dylib             0x000000010a14be5e kevent_qos + 10
    1   libdispatch.dylib                   0x0000000109d13074 _dispatch_mgr_invoke + 248
    2   libdispatch.dylib                   0x0000000109d12e76 _dispatch_mgr_init + 0
    ​
    Thread 2:
    0   libsystem_kernel.dylib             0x000000010a14b4e6 __workq_kernreturn + 10
    1   libsystem_pthread.dylib             0x000000010a16e221 start_wqthread + 13
    ​
    Thread 3:
    0   libsystem_kernel.dylib             0x000000010a14341a mach_msg_trap + 10
    1   CoreFoundation                     0x0000000106f1e7b4 __CFRunLoopServiceMachPort + 212
    2   CoreFoundation                     0x0000000106f1dc31 __CFRunLoopRun + 1345
    3   CoreFoundation                     0x0000000106f1d494 CFRunLoopRunSpecific + 420
    4   Foundation                         0x00000001064d7ff0 -[NSRunLoop runMode:beforeDate:] + 274
    5   Foundation                         0x000000010655f991 -[NSRunLoop runUntilDate:] + 78
    6   UIKit                               0x0000000107e3d539 -[UIEventFetcher threadMain] + 118
    7   Foundation                         0x00000001064e7ee4 __NSThread__start__ + 1243
    8   libsystem_pthread.dylib             0x000000010a16eabb _pthread_body + 180
    9   libsystem_pthread.dylib             0x000000010a16ea07 _pthread_body + 0
    10 libsystem_pthread.dylib             0x000000010a16e231 thread_start + 13
    ​
    Thread 4 Crashed:
    0   RunLoopDemo03                       0x00000001063dfae5 -[PLCrashReporter generateLiveReportWithThread:error:] + 632
    1   RunLoopDemo03                       0x00000001063da728 -[FluencyMonitor handleStackInfo] + 152
    2   RunLoopDemo03                       0x00000001063da2cf runLoopTimerCallBack + 351
    3   CoreFoundation                     0x0000000106f26964 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
    4   CoreFoundation                     0x0000000106f265f3 __CFRunLoopDoTimer + 1075
    5   CoreFoundation                     0x0000000106f2617a __CFRunLoopDoTimers + 250
    6   CoreFoundation                     0x0000000106f1df01 __CFRunLoopRun + 2065
    7   CoreFoundation                     0x0000000106f1d494 CFRunLoopRunSpecific + 420
    8   Foundation                         0x00000001064d7ff0 -[NSRunLoop runMode:beforeDate:] + 274
    9   Foundation                         0x00000001064d7ecb -[NSRunLoop run] + 76
    10 RunLoopDemo03                       0x00000001063d9cbd +[FluencyMonitor monitorThreadEntryPoint] + 253
    11 Foundation                         0x00000001064e7ee4 __NSThread__start__ + 1243
    12 libsystem_pthread.dylib             0x000000010a16eabb _pthread_body + 180
    13 libsystem_pthread.dylib             0x000000010a16ea07 _pthread_body + 0
    14 libsystem_pthread.dylib             0x000000010a16e231 thread_start + 13
    ​
    Thread 4 crashed with X86-64 Thread State:
      rip: 0x00000001063dfae5   rbp: 0x000070000f53fc50   rsp: 0x000070000f53f9c0   rax: 0x000070000f53fa20 
      rbx: 0x000070000f53fb60   rcx: 0x0000000000005e0b   rdx: 0x0000000000000000   rdi: 0x00000001063dfc6a 
      rsi: 0x000070000f53f9f0     r8: 0x0000000000000014     r9: 0xffffffffffffffec   r10: 0x000000010a1433f6 
      r11: 0x0000000000000246   r12: 0x000060800016b580   r13: 0x0000000000000000   r14: 0x0000000000000006 
      r15: 0x000070000f53fa40 rflags: 0x0000000000000206     cs: 0x000000000000002b     fs: 0x0000000000000000 
      gs: 0x0000000000000000 
    

    剩下的工作就是将字符串保存进文件,以及上传到服务器了。

    我们不能将卡顿的阙值定的太小,也不能将所有的卡顿信息都上传,原因有两点,一,太浪费用户流量;二、文件太多,App内存储和上传后服务器端保存都会占用空间。

    可以参考微信的做法,7天以上的文件删除,随机抽取上传,并且上传前对文件进行压缩处理等。

    Crash 收集资料

    原理

    iOS应用崩溃,常见的崩溃信息有EXC_BAD_ACCESSSIGABRTXXXXXXX,而这里分为两种情况,一种是未被捕获的异常,我们只需要添加一个回调函数,并在应用启动时调用一个 API即可;另一种是直接发送的SIGABRT XXXXXXX,这里我们也需要监听各种信号,然后添加回调函数。

    针对情况一,其实我们都见过。我们在收集App崩溃信息时,需要添加一个函数NSSetUncaughtExceptionHandler(&HandleException),参数是一个回调函数,在回调函数里获取到异常的原因,当前的堆栈信息等保存到 dump文件,然后供下次打开App时上传到服务器。

    其实,我们在HandleException回调函数中,可以获取到当前的RunLoop,然后获取该RunLoop中的所有Mode,手动运行一遍。

    针对情况二,首先针对多种要捕获的信号,设置好回调函数,然后也是在回调函数中获取RunLoop,然后拿到所有的Mode,手动运行一遍。

    代码实现

    第一步,我创建了一个处理类,并添加一个单例方法。(代码见末尾的Demo)

    第二步,在单例中对象实例化时,添加 异常捕获 和 signal 处理的 回调函数。

    - (void)setCatchExceptionHandler
    {
      // 1.捕获一些异常导致的崩溃
      NSSetUncaughtExceptionHandler(&HandleException);
    
      // 2.捕获非异常情况,通过signal传递出来的崩溃
      signal(SIGABRT, SignalHandler);
      signal(SIGILL, SignalHandler);
      signal(SIGSEGV, SignalHandler);
      signal(SIGFPE, SignalHandler);
      signal(SIGBUS, SignalHandler);
      signal(SIGPIPE, SignalHandler);
    }
    

    第三步,分别实现 异常捕获的回调 和 signal 的回调。

    void HandleException(NSException *exception)
    {
      // 获取异常的堆栈信息
      NSArray *callStack = [exception callStackSymbols];
      NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
      [userInfo setObject:callStack forKey:kCaughtExceptionStackInfoKey];
    
      CrashHandler *crashObject = [CrashHandler sharedInstance];
      NSException *customException = [NSException exceptionWithName:[exception name] reason:[exception reason] userInfo:userInfo];
      [crashObject performSelectorOnMainThread:@selector(handleException:) withObject:customException waitUntilDone:YES];
    }
    ​
    void SignalHandler(int signal)
    {
      // 这种情况的崩溃信息,就另某他法来捕获吧
      NSArray *callStack = [CrashHandler backtrace];
      NSLog(@"信号捕获崩溃,堆栈信息:%@",callStack);
    
      CrashHandler *crashObject = [CrashHandler sharedInstance];
      NSException *customException = [NSException exceptionWithName:kSignalExceptionName
                                                              reason:[NSString stringWithFormat:NSLocalizedString(@"Signal %d was raised.", nil),signal]
                                                            userInfo:@{kSignalKey:[NSNumber numberWithInt:signal]}];
    
      [crashObject performSelectorOnMainThread:@selector(handleException:) withObject:customException waitUntilDone:YES];
    }
    

    第四步,添加让应用起死回生的 RunLoop 代码

    - (void)handleException:(NSException *)exception
    {
      NSString *message = [NSString stringWithFormat:@"崩溃原因如下:\n%@\n%@",
                            [exception reason],
                            [[exception userInfo] objectForKey:kCaughtExceptionStackInfoKey]];
      NSLog(@"%@",message);
    
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"程序崩溃了"
                                                      message:@"如果你能让程序起死回生,那你的决定是?"
                                                      delegate:self
                                            cancelButtonTitle:@"崩就蹦吧"
                                            otherButtonTitles:@"起死回生", nil];
      [alert show];
    
      CFRunLoopRef runLoop = CFRunLoopGetCurrent();
      CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop);
    
      while (!ignore) {
          for (NSString *mode in (__bridge NSArray *)allModes) {
              CFRunLoopRunInMode((CFStringRef)mode, 0.001, false);
          }
      }
    
      CFRelease(allModes);
    
      NSSetUncaughtExceptionHandler(NULL);
      signal(SIGABRT, SIG_DFL);
      signal(SIGILL, SIG_DFL);
      signal(SIGSEGV, SIG_DFL);
      signal(SIGFPE, SIG_DFL);
      signal(SIGBUS, SIG_DFL);
      signal(SIGPIPE, SIG_DFL);
    
      if ([[exception name] isEqual:kSignalExceptionName]) {
          kill(getpid(), [[[exception userInfo] objectForKey:kSignalKey] intValue]);
      } else {
          [exception raise];
      }
    }
    

    因为我这里弄了一个AlertView弹窗,所以必须要回到主线程来处理。 实际上,RunLoop 相关的代码:

    CFRunLoopRef runLoop = CFRunLoopGetCurrent();
      CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop);
    
      while (!ignore) {
          for (NSString *mode in (__bridge NSArray *)allModes) {
              CFRunLoopRunInMode((CFStringRef)mode, 0.001, false);
          }
      }
    
      CFRelease(allModes);
    

    完全可以写在 上面的 HandleException 回调 和 SignalHandler回调中。

    第五步,写一段会导致崩溃的代码

    我是在ViewController 中添加了一个点击事件,弄了一个数组越界的Bug:

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
      NSArray *array =[NSArray array];
      NSLog(@"%@",[array objectAtIndex:1]);
    }
    

    动态效果图:

    727768-5a47f8c85afebb6d.gif

    遇到数组越界,应用依然没崩溃

    sunnyxx 称之为回光返照,为什么呢? 我再一次点击视图,应用依然还是崩溃了,只能防止第一次崩溃。 我测试了,确实是第二次应用崩溃,未能起死回生。

    相关文章

      网友评论

        本文标题:iOS-RunLoop在实际开发过程中的应用

        本文链接:https://www.haomeiwen.com/subject/oknnjqtx.html