2012-09-10 94 views
1

這是我的程序的一部分。按下按鈕後,findDuplicates循環將在後臺線程中啓動。有什麼辦法通過按另一個按鈕來停止/終止線程/循環?如何終止循環/線程

- (IBAction)countDups:(id)sender { 
    [self performSelectorInBackground:@selector(findDuplicates) withObject:nil]; 
} 

-(void)findDuplicates 
{ 
... 
for(int index=0;index<self.resultList.count;index++) 
{ ... } 
... 
} 

回答

2

您可以從後臺線程返回。創建一個成員變量,用NO進行初始化。

- (IBAction)countDups:(id)sender { 
    mCancel = NO; 
    [self performSelectorInBackground:@selector(findDuplicates) withObject:nil]; 
} 

-(IBAction)stop 
{ 
    mCancel = YES; //BOOL member variable; 
} 

-(void)findDuplicates 
{ 
... 
for(int index=0;index<self.resultList.count;index++) 
{ 
    If(mCancel) 
    return; // return for thread to end 

    ... } 
... 
}