开发者

How to stop a NSThread sub-thread in iphone

开发者 https://www.devze.com 2023-01-06 10:45 出处:网络
I created a sub-thread 开发者_如何学运维using NSThread in main thread NSThread *newThread = [[NSThread alloc] initWithTarget:self selector:@selector(MyThread:) object:timer];

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.


-(void)cancel

Discussion The semantics of this method are the same as those used for the NSOperation object. This method sets state information in the receiver that is then reflected by the isCancelled method. Threads that support cancellation should periodically call the isCancelled method to determine if the thread has in fact been cancelled, and exit if it has been.

more information see NSThread API Reference

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号