解析在iPhone应用中NSThread创建Run Loop

iPhone应用中NSThread创建Run Loop是本文要介绍的内容,虽然iphone为我们提供了很多简单易于操作的线程方法。 
IPhone多线程编程提议用NSOperation和NSOperationQueue,这个确实很好用。 
但是有些情况下,我们还是在运行一些长线任务或者复杂任务的时候需要用比较原始的NSThread。这就需要为NSThread创建一个run loop. 
[pre]NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(playerThread: ) object:nil];  

    1. [thread start];  

//如果要利用NSOperation,原理类似。只需要加入到queue里面去就好了。。queue会在合适的时机调用方法,下面代码作为参考。

- (void) playerThread: (void*)unused   

{   

audioRunLoop = CFRunLoopGetCurrent();//子线程的runloop引用  

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];//子线程的  run loop

[self initPlayer];

CFRunLoopRun(); //运行子线程的  run loop,这里就会停住了。

[pool release];  

}

 

// 实现一个timer,用于检查子线程的工作状态,并在合适的时候做任务切换。或者是合适的时候停掉自己的  run loop

-(void) initPlayer {   

// 在这里你可以初始化一个工作类,比如声音或者视频播放   

NSTimer *stateChange = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:  

   @selector(checkStatuserInfo:nil repeats:YES];  

}  

-(void) checkState:(NSTimer*) timer   

{   

if(需要退出自线程了) {  

//释放子线程里面的资源  

CFRunLoopStop( CFRunLoopGetCurrent());//结束子线程任务  }   

}

posted on 2014-11-09 02:46  Jason_Luo  阅读(240)  评论(0编辑  收藏  举报

导航