#import "text.h"
@interface text ()
{
NSTimer *timer;
}
@end
@implement text
- (void)start {
_timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(text)
userInfo:nil
repeats:yes];
}
- (void)text{
nslog(@"LOL");
}
- (void)dealloc {
[_timer invaildate];
}
1.该例子中由nstimer导致了循环引用,dealloc永远不会被调用,因为使用nstimer定时调用某方法时,会对目标对象进行强引用,只有在调用invaildate方法后,才会进行计数器-1,而该例子中由于循环调用self中的text方法,而invalidate方法在dealloc中,导致定时器无法停止,self也无法释放。
2.为了避免该循环引用,可以把invalidate放在text中调用。
3.NSTimer定时器的用法:
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 = [NSTimertimerWithTimeInterval:3.0 target:selfselector:@selector(timerFired:) userInfo:nilrepeats:NO];
[[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSDefaultRunLoopMode];
2、触发(启动)
当定时器创建完(不用scheduled的,添加到runloop中后,该定时器将在初始化时指定的timeInterval秒后自动触发。
可以使用-(void)fire;方法来立即触发该定时器;
注:
在重复执行的定时器中调用此方法后立即触发该定时器,但不会中断其之前的执行计划;
在不重复执行的定时器中调用此方法,立即触发后,就会使这个定时器失效。
3、停止
- (void)invalidate;
这个是唯一一个可以将计时器从runloop中移出的方法。
注:
NSTimer可以精确到50-100毫秒.