您的位置:首页 > 移动开发 > IOS开发

NSThread 和 NSTimer

2013-04-27 17:40 417 查看
   在自己定义的线程中使用NSTimer,如果对线程了解的不够很容易导致timer要调用的函数无法调用。     在新的线程中使用NSTimer如下所示
-(IBAction)hehe:(id)sender{NSThread*thread=[[NSThreadalloc]initWithTarget:self 
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过去了.推荐几篇文章:http://www.dreamingwish.com/dream-2012/ios-multithread-program-runloop-the.htmlhttp://blog.163.com/ray_jun/blog/static/16705364220124461711310/都是关于NSRunLoop的。

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS 多线程 NSRunLoop