(转)[IOS]Timer定时器

本文介绍了在iOS开发中如何使用NSTimer来实现定时任务。详细解释了两种创建NSTimer的方法及其区别,并提供了启动和停止定时器的示例代码。

转自:http://blog.youkuaiyun.com/springjustin/article/details/50978671

 

NSTimer

方式1

    // 创建定时器

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

 

    // 停止定时器

    [timer invalidate];

 

方式2

    // 创建定时器

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

    // 将定时器添加到runloop中,否则定时器不会启动

    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

 

    // 停止定时器

    [timer invalidate];

方式1会自动将创建的定时器以默认方式添加到当前线程runloop中,而无需手动添加。但是在此种模式下,当滚动屏幕时runloop会进入另外一种模式,定时器会暂停,为了解决这种问题,可以像方式2那样把定时器添加到NSRunLoopCommonModes模式下。

方式1和方式2在设置后都会在间隔设定的时间(本例中设置为2s)后执行test方法,如果需要立即执行可以使用下面的代码。

注销定时器:[time fire];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值