NSTimer的一些用法

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeaction:) userInfo:@"liyang" repeats:NO];
       NSTimer *tt= [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeaction:) userInfo:@"limengxia" repeats:NO];
        [[NSRunLoop currentRunLoop]addTimer:tt forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop]run];
//NSRunLoop的理解,每一个线程都有一个NSRunLoop对象,然而定时器也是在这个对象上面运行的,当一个线程运行完成了过后,会自动关闭线程,自然NSRunLoop也会被销毁,自然定时器就不会运行,为了不让其线程关闭,用此语句     [[NSRunLoop currentRunLoop]run];那么线程就会保持活跃状态,不会被关闭,自然定时器也就能用了,[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeaction:) userInfo:@"liyang" repeats:NO];这么设置的定时器是自动添加到了NSRunLoop中的, NSTimer *tt= [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeaction:) userInfo:@"limengxia" repeats:NO];这个定时器需要手动添加 [[NSRunLoop currentRunLoop]addTimer:tt forMode:NSDefaultRunLoopMode];

1、初始化

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

注:不用scheduled方式初始化的,需要手动addTimer:forMode: 将timer添加到一个runloop中。

  而scheduled的初始化方法将以默认mode直接添加到当前的runloop中.

 

举例:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];

NSTimer *myTimer = [NSTimer  timerWithTimeInterval:3.0 target:selfselector:@selector(timerFired:)userInfo:nilrepeats:NO];

[[NSRunLoop  currentRunLoopaddTimer:myTimerforMode:NSDefaultRunLoopMode];

 

2、触发(启动)

当定时器创建完(不用scheduled的,添加到runloop中后,该定时器将在初始化时指定的timeInterval秒后自动触发。

 

可以使用-(void)fire;方法来立即触发该定时器;

注:You can use this method to fire a repeating timer without interrupting its regular firing schedule. If the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived.

在重复执行的定时器中调用此方法后立即触发该定时器,但不会中断其之前的执行计划;

在不重复执行的定时器中调用此方法,立即触发后,就会使这个定时器失效。

 

3、停止

- (void)invalidate;

这个是唯一一个可以将计时器从runloop中移出的方法。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值