如何在iphone中停止NSThread子线程

Non*_*one 8 iphone objective-c nsthread

我在主线程中使用NSThread创建了一个子线程

NSThread *newThread = [[NSThread alloc] initWithTarget:self selector:@selector(MyThread:) object:timer];

5秒后,我在主线程中使用[newThread cancel]来停止子线程,但它没有用,

方法MyThread:在newThread中仍然有效

那么,什么是正确的答案来停止newThread,THX

实际上[newThread isCancelled]是YES,但是选择器MyThread仍在进行中

moh*_*enr 10

cancel方法只通知线程,它被取消(正如你所提到的变化isCancelled,以YES它当时线程本身来检查这个退出的责任.例如,在你的.MyThread:方法,你可以这样做:

// At some checkpoint
if([[NSThread currentThread] isCancelled]) {
    /* do some clean up here */
    [NSThread exit];
}
Run Code Online (Sandbox Code Playgroud)

你应该定期检查,并从线程中退出,如图所示; 否则cancel没有任何影响.