解析在iPhone應用中NSThread創(chuàng)建Run Loop
作者:佚名
IPhone多線程編程提議用NSOperation和NSOperationQueue,這個確實很好用。但是有些情況下,我們還是在運行一些長線任務或者復雜任務的時候需要用比較原始的NSThread。來看內(nèi)容。
在iPhone應用中NSThread創(chuàng)建Run Loop是本文要介紹的內(nèi)容,雖然iphone為我們提供了很多簡單易于操作的線程方法。IPhone多線程編程提議用NSOperation和NSOperationQueue,這個確實很好用。但是有些情況下,我們還是在運行一些長線任務或者復雜任務的時候需要用比較原始的NSThread。這就需要為NSThread創(chuàng)建一個run loop.
- NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(playerThread: ) object:nil];
- [thread start];
- //如果要利用NSOperation,原理類似。只需要加入到queue里面去就好了。。queue會在合適的時機調(diào)用方法,下面代碼作為參考。
- - (void) playerThread: (void*)unused
- {
- audioRunLoop = CFRunLoopGetCurrent();//子線程的runloop引用
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];//子線程的
- run loop [self initPlayer]; CFRunLoopRun(); //運行子線程的
- run loop,這里就會停住了。 [pool release];
- }
- // 實現(xiàn)一個timer,用于檢查子線程的工作狀態(tài),并在合適的時候做任務切換?;蛘呤呛线m的時候停掉自己的
- 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());//結(jié)束子線程任務
- }
- }
小結(jié):解析在iPhone應用中NSThread創(chuàng)建run loop的內(nèi)容介紹完了,希望本文對你有所幫助!
【編輯推薦】
- 關(guān)于iPhone多線程編程的教程
- iPhone游戲開發(fā)者需知6點建議
- iPhone開發(fā)應用之Archiving NSCoder教程
- iPhone開發(fā)應用中關(guān)于CFRunLoop學習
- 關(guān)于iPhone開發(fā)類NSDate常用代碼案例
責任編輯:zhaolei
來源:
互聯(lián)網(wǎng)