timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(dealTimer) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
2.将计数器的repeats设置为Yes的时候,self的引用计数会加1.因此可能会导致self(即viewController)不能release,所以,必须在viewDisappear的时候,将计数器timer停止,否则可能会导致内存泄漏。
- (void)viewDidDisappear:(BOOL)animated {
[timer invalidate];
timer = nil;
}
3.当程序退出到后台时,应当暂停定时器,当再次进入前台时再次开启定时器.避免定时器在不必要的时候一直运行,占用cpu
在viewDidLoad方法中响应系统通知:
[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(enterActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(enterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
实现通知方法:
- (void)enterActive:(NSNotification*)noti{
// 程序进入前台,开启定时器
[timer setFireDate:[NSDate distantPast]];
}
- (void)enterBackground:(NSNotification *)noti {
// 程序进入后台,关闭定时器
[timer setFireDate:[NSDate distantFuture]];
}