IOS 中NSTimer使用注意事项

文章来源:http://www.itnose.net/detail/6043298.html 更多文章:http://www.itnose.net/type/84.html

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;

注意:userInfo是值NSTimer携带的用户信息。

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

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

sample:

    [NSTimer scheduledTimerWithTimeInterval:2 target:selfselector:@selector(startFindApartment:) userInfo:nil repeats:YES];

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

[[NSRunLoopcurrentRunLoop] addTimer:myTimerforMode:NSDefaultRunLoopMode];

2、触发(启动)

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

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

    NSRunLoop *runLoop=[NSRunLoop currentRunLoop];

    [runLoop addTimer:timer forMode:NSDefaultRunLoopMode];

    [timer fire];

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

3、停止

- (void)invalidate;

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

4、在多线程开发中,如果是在mainthread中使用定时器,两种初始化方法都能使用,如果是在子线程中使用定时器,只能使用方法:

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

 
并且启动定时器不能用fire,只能让runloop一直执行下去,sample code:

_timer=[NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(timeSchedule) userInfo:nil repeats:YES];

    NSRunLoop *runLoop=[NSRunLoop currentRunLoop];

    [runLoop addTimer:_timer forMode:NSDefaultRunLoopMode];

    while ([runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);

猜你喜欢

转载自twobrushes.iteye.com/blog/2067260