I created a sub-thread using NSThread in main thread
NSThread *newThread = [[NSThread alloc] initWithTarget:self selector:@selector(MyThread:) object:timer];
5 sec later,i used [newThread cancel] in main thread to stop the sub-thread,but it didnt work,
Method MyThread: in newThread still working
so,whats the correct answer to stop newThread,THX
actually [newThread isCancelled] is YES,but selector MyThread was still woking
The cancel method only informs the thread that it is cancelled (as you mentioned changes the isCancelled to YES. It's then the responsibility of the thread itself to check this and exit. For example, in your MyThread: method you could do this:
// At some checkpoint
if([[NSThread currentThread] isCancelled]) {
/* do some clean up here */
[NSThread exit];
}
You should do this check periodically, and exit from within the thread as shown; otherwise the cancel doesn't have any effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With