解析在iPhone應(yīng)用中NSThread創(chuàng)建Run Loop
在iPhone應(yīng)用中NSThread創(chuàng)建Run Loop是本文要介紹的內(nèi)容,雖然iphone為我們提供了很多簡單易于操作的線程方法。IPhone多線程編程提議用NSOperation和NSOperationQueue,這個(gè)確實(shí)很好用。但是有些情況下,我們還是在運(yùn)行一些長線任務(wù)或者復(fù)雜任務(wù)的時(shí)候需要用比較原始的NSThread。這就需要為NSThread創(chuàng)建一個(gè)run loop.
- NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(playerThread: ) object:nil];
- [thread start];
- //如果要利用NSOperation,原理類似。只需要加入到queue里面去就好了。。queue會(huì)在合適的時(shí)機(jī)調(diào)用方法,下面代碼作為參考。
- - (void) playerThread: (void*)unused
- {
- audioRunLoop = CFRunLoopGetCurrent();//子線程的runloop引用
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];//子線程的
- run loop [self initPlayer]; CFRunLoopRun(); //運(yùn)行子線程的
- run loop,這里就會(huì)停住了。 [pool release];
- }
- // 實(shí)現(xiàn)一個(gè)timer,用于檢查子線程的工作狀態(tài),并在合適的時(shí)候做任務(wù)切換?;蛘呤呛线m的時(shí)候停掉自己的
- run loop-(void) initPlayer {
- // 在這里你可以初始化一個(gè)工作類,比如聲音或者視頻播放
- NSTimer *stateChange = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:
- @selector(checkStatuserInfo:nil repeats:YES];
- }
- -(void) checkState:(NSTimer*) timer
- {
- if(需要退出自線程了) {
- //釋放子線程里面的資源
- CFRunLoopStop( CFRunLoopGetCurrent());//結(jié)束子線程任務(wù)
- }
- }
小結(jié):解析在iPhone應(yīng)用中NSThread創(chuàng)建run loop的內(nèi)容介紹完了,希望本文對(duì)你有所幫助!
【編輯推薦】
- 關(guān)于iPhone多線程編程的教程
- iPhone游戲開發(fā)者需知6點(diǎn)建議
- iPhone開發(fā)應(yīng)用之Archiving NSCoder教程
- iPhone開發(fā)應(yīng)用中關(guān)于CFRunLoop學(xué)習(xí)
- 關(guān)于iPhone開發(fā)類NSDate常用代碼案例