开发者

performSelector NSThread issue

开发者 https://www.devze.com 2023-02-17 16:38 出处:网络
Is it possible to cancel a thread while performSelector waitsUntilDone? See below: I have a while loop with following line:

Is it possible to cancel a thread while performSelector waitsUntilDone?

See below:

I have a while loop with following line:

[self performSelector:@selector(getMyRecords:) onThread:myThread withObject:i waitUntilDone:YES]

Sometimes, I need to cancel my thread myThread while my loop executes. I get following crash issue:

Terminating app due to uncaught exception 'NSDestinationInvalidException', reason: '*** -[MyController performSelect开发者_运维问答or:onThread:withObject:waitUntilDone:modes:]: target thread exited while waiting for the perform'


if you have a long running operation inside a thread, you can declare a condition variable (atomic) like 'canceled' and check it. something like:

- (void) threadFunc {
 while (!canceled){
   // do stuff
 }
}


- (void) cancelThread {
 canceled = true;
}


I think the easiest way is to use NSThread's -(void)cancel method.


Check out the documentation of NSObject:

This method queues the message on the run loop of the target thread using the default run loop modes—that is, the modes associated with the NSRunLoopCommonModes constant. As part of its normal run loop processing, the target thread dequeues the message (assuming it is running in one of the default run loop modes) and invokes the desired method.

You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method.

This method retains the receiver and the arg parameter until after the selector is performed.

0

精彩评论

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