performSelector NSThread issue

末鹿安然 提交于 2020-02-25 04:35:35

问题


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 performSelector:onThread:withObject:waitUntilDone:modes:]: target thread exited while waiting for the perform'

回答1:


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.




回答2:


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;
}



回答3:


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



来源:https://stackoverflow.com/questions/5324526/performselector-nsthread-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!