在自己定义的线程中使用NSTimer,如果对线程了解的不够很容易导致timer要调用的函数无法调用。
在新的线程中使用NSTimer如下所示
- (IBAction)hehe:(id)sender
{ NSThread* thread = [[NSThread alloc] initWithTarget:selfselector:@selector(timerStart)
object:nil];
[thread start];
}
-(void)timerStart
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:5
target:self
selector:@selector(method)
userInfo:nil
repeats:YES];
/*
用
[NSTimer schduledTimerWithTimeInterval: target:selector:userInfo:repeats];
会自动把nstimer加到当前线程的runloop中,
也可以手动制定添加到自己新建的NSRunLoop的中
NSTimer *timer = [NSTimer timerWithTimeInterval: invocation:repeates:];
NSTimer *timer = [[NSTimer alloc] initWithFireDate:...];
创建timer [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
注意 timer的释放
*/
[
[NSRunLoop currentRunLoop] run];
/*
新建一个NSThread不会自动创建Run Loop循环(注意是Run Loop循环,runloop本身是自动创建的,而不是循环,这个循环其实就是消息队列循环),这时候需要我们手动创建一个runloop循环以使timer在此线程中良好的运行。
*/
[pool release]; }
关于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 *timer = [NSTimertimerWithTimeInterval:3.0 target:selfselector:@selector(timerFired:)userInfo:nilrepeats:NO];
[[NSRunLoopcurrentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
2、立即触发(启动)
当定时器创建完(不用scheduled的,添加到runloop中后使用-(void)fire;方法
来立即触发该定时器实验表明只执行一次,尽管repeats设为yes;
在不重复执行的定时器中调用此方法,立即触发后,就会使这个定时器失效。
3、停止
- (void)invalidate;
这个是唯一一个可以将计时器从runloop中移出的方法。
小注:
NSTimer可以精确到50-100毫秒.(间隔太小频繁的中断处理机,以致大量的时间浪费在调度上)
NSTimer不是绝对准确的,而且中间耗时或阻塞错过下一个点,那么下一个点就pass过去了.
推荐几篇文章:
http://www.dreamingwish.com/dream-2012/ios-multithread-program-runloop-the.html
http://blog.163.com/ray_jun/blog/static/16705364220124461711310/
都是关于NSRunLoop的。