NSThread 和 NSTimer

      在自己定义的线程中使用NSTimer,如果对线程了解的不够很容易导致timer要调用的函数无法调用。    

      在新的线程中使用NSTimer如下所示

 

- (IBAction)hehe:(id)sender

{ NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@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的。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值