Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a NSThread sub-thread in iphone

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

like image 256
None Avatar asked Jul 07 '10 01:07

None


1 Answers

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.

like image 154
mohsenr Avatar answered Sep 16 '22 15:09

mohsenr