標籤:
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 線程處理 子線程