注意:定时器的调用,放在主线程中最优! 在gcd dispatch_async中执行可能会无效
初始化方法:(2种)
(1)+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;//不会将它添加到主循环中
(2)+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;//系统自动将其添加到主循环中
(1)补充代码
//将定时器假如主循环中
[[NSRunLoop mainRunLoop] addTimer:self.time forMode:NSDefaultRunLoopMode];
[NSTimer scheduledTimerWithTimeInterval:1.0/60 target:self selector:@selector(moveAction) userInfo:nil repeats:YES];
//触发定时器调用方法
-(void)moveAction{
for (zombA *zomb1 in self.zombCount) {
zomb1.center = CGPointMake(zomb1.center.x - zomb1.speed, zomb1.center.y);
if (zomb1.center.x <= -20) {
[zomb1 removeFromSuperview];
[self.zombCount removeObject:zomb1];
break;
}
}
}
例子:比如,在页面消失的时候关闭定时器,然后等页面再次打开的时候,又开启定时器。(主要是为了防止它在后台运行,暂用CPU)可以使用下面的代码实现:
//页面将要进入前台,开启定时器
-(void)viewWillAppear:(BOOL)animated
{
//开启定时器
[scrollView.myTimer setFireDate:[NSDate distantPast]];
}
//页面消失,进入后台不显示该页面,关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
//关闭定时器
[scrollView.myTimer setFireDate:[NSDate distantFuture]];
}
//取消定时器
[self.time invalidate];
self.time = nil;