NSOperation和NSNotificationCenter在主线程上 [英] NSOperation and NSNotificationCenter on the main thread
问题描述
我有一个NSOperation。当它完成后,我触发一个NSNotificationCenter让程序知道NS操作完成并更新gui。
I have an NSOperation. When it is finished I fire a NSNotificationCenter to let the program know that the NSoperation is finished and to update the gui.
对我来说,NSNotification的侦听器不会运行主线程因为NSOperation不在主线程上。
To my understanding listeners to the NSNotification will not run on the main thread because the NSOperation is not on the main thread.
我如何做,以便侦听器在我的事件触发时在主线程上运行?
How can I make it so that the listeners run on the main thread when I fire my event?
[[NSNotificationCenter defaultCenter] postNotificationName:@"myEventName" object:self];
推荐答案
您可以使用 performSelectorOnMainThread:withObject:waitUntilDone:
。使用辅助方法,类似于以下示例。
You can use performSelectorOnMainThread:withObject:waitUntilDone:
with using a helper method, in a similar fashion to the following example.
.....
[self performSelectorOnMainThread:@selector(fireNotification) withObject:nil waitUntilDone:YES];
...
- (void)fireNotification {
[[NSNotificationCenter defaultCenter] postNotificationName:@"myEventName" object:self];
}
如果你不等到完成,你需要考虑其他线程可能引用在主线程被调用之前已经清理的对象。
If you don't wait until being done, you will need to consider the cases where other threads may refer to the object which could be already cleaned up before the main thread gets invoked.
这篇关于NSOperation和NSNotificationCenter在主线程上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!