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


  本文标签:iPhone NSThread Run Loop

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

  1. NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(playerThread: ) object:nil];  
  2. [thread start];  
  3. //如果要利用NSOperation,原理类似  。只需要加入到queue里面去就好了  。  。queue会在合适的时机调用方法,下面代码作为参考  。  
  4. - (void) playerThread: (void*)unused   
  5. {   
  6. audioRunLoop = CFRunLoopGetCurrent();//子线程的runloop引用  
  7. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];//子线程的  
  8. run loop [self initPlayer]; CFRunLoopRun(); //运行子线程的  
  9. run loop,这里就会停住了  。 [pool release];  
  10. }  
  11.  // 实现一个timer,用于检查子线程的工作状态,并在合适的时候做任务切换  。或者是合适的时候停掉自己的  
  12.  run loop-(void) initPlayer {   
  13.  // 在这里你可以初始化一个工作类,比如声音或者视频播放   
  14.  NSTimer *stateChange = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:  
  15.    @selector(checkStatuserInfo:nil repeats:YES];  
  16.  }  
  17.  -(void) checkState:(NSTimer*) timer   
  18.  {   
  19.  if(需要退出自线程了) {  
  20.  //释放子线程里面的资源  
  21.  CFRunLoopStop( CFRunLoopGetCurrent());//结束子线程任务  
  22.  }   

  小结:解析在iPhone应用中NSThread创建run loop的内容介绍完了,希望本文对你有所帮助!