iOS 定时器的难点

实际开发中,大家会遇到的一个场景是:以+ scheduledTimerWithTimeInterval...的方式实例化的timer对象,作用在UIScrollView上的列表时,timer会暂定回调,在没弄明白其原理的情况,很是抓狂。在查看官方文档和大神们的日记后终于搞明白了。

 

>创建定时器有两种方式:+scheduledTimerWithTimeInterval、+timerWithTimeInterval。

// 第一种创建定时器方法(多数情况使用这一种方法)

    // scheduledTimerWithTimeInterval:本质做了两件事情:

    // > 创建了一个定时器对象

    // > 将定时器监听方法注册到了runLoop(运行循环)里面,以默认NSDefaultRunLoopMode模式添加,这就导致了如果在UIScrollView上,拖动列表时,timer会暂定回调

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];

    // 需要手动将定时器以NSRunLoopCommonModes模式添加到运行循环中,如果定时器没有失效,会一直运行下去

    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

 

// 第二种创建定时器方法

    // timerWithTimeInterval:该方法创建的定时器对象默认没有被添加到运行循环,需要手动注册到runLoop(运行循环)里面

    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];

    // 只要将定时器对象添加到运行循环,就会自动开启定时器

    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

    // 该方法只会触发一次回调方法。

    [timer fire];

 

>当不需要定时器的时候,记得将定时器移除

  // 让定时器失效:一旦定时器失效,则不能再使用,只能重新创建一个新的定时器

    [timer invalidate];

    timer = nil;

 

posted @ 2015-07-08 00:06  子涛  阅读(254)  评论(0编辑  收藏  举报