IOS 線程處理 子線程

來源:互聯網
上載者:User

標籤:

IOS中,如果要在主線程中啟動一個子線程,可以又兩種方法:


[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil]; 
這是在cocoa早期提供的方法,因此你可以在任何版本的ios和mac上調用此方法。
在 OS X v10.5(or later)和IOS中,蘋果又提供了一種方法,可以允許你獲得你的thread控制代碼,並且更方便的讓主線程式控制制子線程。

 
NSThread* myThread = [[NSThread alloc] initWithTarget:self 
                                        selector:@selector(myThreadMainMethod:) 
                                        object:nil]; 
[myThread start];  // Actually create the thread 

如果要停止子線程,有兩種方法:
第一種,是在子線程中執行:


[NSThread exit]; 

另一種是在主線程執行:

[myThread cancel];  
要注意的是,[mThread cancel]; 並不能exit線程,只是標記為canceled,但線程並沒有死掉。加入你在子線程中執行了一個迴圈,則cancel後,迴圈還在繼續,你需要在迴圈的條件判斷中加入 !mThread.isCancelled 來判斷子線程是否已經被cancel來決定是否繼續迴圈。

下面是我的一個測試demo,可以參考一下:

@synthesize mThread; 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
     
    NSLog(@"main thread:%@",[NSThread currentThread]); 
     mThread=[[NSThread alloc] initWithTarget:self selector:@selector(subThreadMethod) object:nil]; 
    [NSThread detachNewThreadSelector:@selector(performMethod) toTarget:self withObject:nil]; 
  
} 
-(void)subThreadMethod{ 
    int i=1; 
    while (i++>0 && ![[NSThread currentThread]isCancelled]) { 
        NSLog(@"subthread i:%d ,thread:%@",i,[NSThread currentThread]); 
    }   
} 
 
- (IBAction)startThread:(id)sender { 
    NSLog(@"startThread...."); 
    [mThread start]; 
} 
 
- (IBAction)stopThread:(id)sender { 
    NSLog(@"mThread.isCancelled: %d",mThread.isCancelled); 
    if (!mThread.isCancelled) { 
        [mThread cancel]; 
//        [mThread exit]; //exit 是類方法,不可以用在對象上 
    } 
} 
 
- (IBAction)performOnSubThread:(id)sender { 
    //在子線程調用方法 
     [self performSelector:@selector(performMethod) onThread:mThread withObject:nil waitUntilDone:NO]; 
} 
-(void)performMethod{ 
    NSLog(@"performMethod.... thread:%@",[NSThread currentThread]);     
} 
@end

 

 

轉自 http://www.cnblogs.com/ygm900/archive/2013/05/26/3100076.html

IOS 線程處理 子線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.