码迷,mamicode.com
首页 > 其他好文 > 详细

七、定时器的难点

时间:2015-07-08 02:03:47      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

实际开发中,大家会遇到的一个场景是:以+ 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;

 

七、定时器的难点

标签:

原文地址:http://www.cnblogs.com/muqizi/p/4628927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!