NSThread 和 NSTimer
2013-04-27 17:40
417 查看
在自己定义的线程中使用NSTimer,如果对线程了解的不够很容易导致timer要调用的函数无法调用。 在新的线程中使用NSTimer如下所示-(IBAction)hehe:(id)sender{NSThread*thread=[[NSThreadalloc]initWithTarget:self http://www.dreamingwish.com/dream-2012/ios-multithread-program-runloop-the.htmlhttp://blog.163.com/ray_jun/blog/static/16705364220124461711310/都是关于NSRunLoop的。
selector:@selector(timerStart)
object:nil];
[threadstart];}-(void)timerStart{NSAutoreleasePool*pool=[[NSAutoreleasePoolalloc]init];
timer=[NSTimerscheduledTimerWithTimeInterval:5
target:self
selector:@selector(method)
userInfo:nil
repeats:YES];
/*
用[/code][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的释放
*/
[[/code]
[NSRunLoopcurrentRunLoop]run];
/*
新建一个NSThread不会自动创建RunLoop循环(注意是RunLoop循环,runloop本身是自动创建的,而不是循环,这个循环其实就是消息队列循环),这时候需要我们手动创建一个runloop循环以使timer在此线程中良好的运行。
*/
[poolrelease];}关于NSTimer1、初始化+(NSTimer*)timerWithTimeInterval:(NSTimeInterval)titarget:(id)aTargetselector:(SEL)aSelectoruserInfo:(id)userInforepeats:(BOOL)yesOrNo;+(NSTimer*)scheduledTimerWithTimeInterval:(NSTimeInterval)titarget:(id)aTargetselector:(SEL)aSelectoruserInfo:(id)userInforepeats:(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过去了.推荐几篇文章:
相关文章推荐
- iOS多线程编程(四)NSRunLoop初步概念以及NSTimer在NSThread中的使用
- NSTimer、 NSTask、 NSThread 和 NSRunloop 之间的区别
- NSTimer、 NSTask、 NSThread 和 NSRunloop
- NSTimer、 NSTask、 NSThread 和 NSRunloop 之间的区别
- NSTimer、 NSTask、 NSThread 和 NSRunloop 之间的区别:
- NSTimer、 NSTask、 NSThread 和 NSRunloop 之间的区别:
- nstimer,nsrunloop,nsthread,nstask
- NSTimer、 NSTask、 NSThread 和 NSRunloop 之间的区别
- NSThread,NSOperation,NSTimer
- iOS多线程编程(四)NSRunLoop初步概念以及NSTimer在NSThread中的使用
- ios30---pthread, NSThread, GCD, NSOperation
- iOS【NSTimer到底准不准?】
- 【iOS沉思录】如何创建NSTimer并使其在当前线程中正常运行?
- NSTimer
- dispatch_async 与 NSThread 创建一个任务(更新界面)
- 在新线程中使用NSTimer
- iphone定时器--NSTimer
- 延时函数和NSTimer的使用
- IOS 定时器NSTimer的使用
- 用NSTimer实现倒计时--ios开发