定时器用法总结

NSTimer在IOS开发中会经常用到,尤其是小型游戏,然而对于初学者时常会注意不到其中的内存释放问题,将其基本用法总结如下:

方法 1

NSInvocation *invo = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(f)]];
[invo setTarget:self];
[invo setSelector:@selector(myLog)];
time = [NSTimer timerWithTimeInterval:1 invocation:invo repeats:YES];
[time fire];
[[NSRunLoop mainRunLoop] addTimer:time forMode:NSDefaultRunLoopMode];

方法 2

time = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(myLog) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:time forMode:NSDefaultRunLoopMode];
[time fire];

方法 3

time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(myLog) userInfo:nil repeats:YES];
[time fire];

方法 4

NSInvocation *invo = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(myLog)]];
[invo setTarget:self];
[invo setSelector:@selector(myLog)];
time = [NSTimer scheduledTimerWithTimeInterval:1 invocation:invo repeats:YES];
[time fire];

方法 5

time = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:1 target:self selector:@selector(myLog) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:time forMode:NSDefaultRunLoopMode];

关于内存释放

如果我们启动了一个定时器,在某个界面释放前,将这个定时器停止,甚至置为nil,都不能是这个界面释放,原因是系统的循环池中还保有这个对象。

[timer invalidate];

在官方文档中我们可以看到 [timer invalidate]是唯一的方法将定时器从循环池中移除。