是否可以使用通知回复到IOS应用程序的主线程? (cf performSelectorOnMainThread) [英] is it ok to use of a notification to communication back to the main thread of an IOS app? (cf performSelectorOnMainThread)

查看:202
本文介绍了是否可以使用通知回复到IOS应用程序的主线程? (cf performSelectorOnMainThread)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用通知回复到IOS应用程序的主线程? (cf performSelectorOnMainThread)。也就是说,有没有为此目的的gottcha?

Is it ok to use of a notification to communication back to the main thread of an IOS app? (cf performSelectorOnMainThread). That is, there are are there any gottcha's for this purpose?

背景


  • 想要从后台线程回调主UI线程(例如performSelectorInBackground)

  • 可以使用performSelectorOnMainThread进行回传,但想知道是否可以使用通知?

例如

 [[NSNotificationCenter defaultCenter] postNotificationName:@"ModelChanged" object:self];


推荐答案

实际上有一个gottcha;你会随机崩溃!这是我的经历。这与接收通知的对象在与通知的发件人相同的线程上这样做的事实有关。

Actually there is a gottcha; you'll crash randomly! That has been my experience. This has to do with the fact that the object receiving the notification does so on the same thread as the notification's sender.

来自通知中心的Apple iOS文档


在多线程应用程序中,通知始终以
的形式发送通知发布的线程,其中可能不是
相同的线程观察者注册了自己。

In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself.

这将不可避免地导致您头痛。

This will inevitably cause you headaches.

如果主线程上的某些东西收到通知,我发现从后台线程弹出主线程发出通知是最安全的方法。这很简单:

If the notification is being received by something on the main thread, I've found that popping into the main thread from the background thread to issue a notification is the safest way to go about this. It is quite simple to do:

//Call this to post a notification and are on a background thread      
- (void) postmyNotification{
  [self performSelectorOnMainThread:@selector(helperMethod:) withObject:Nil waitUntilDone:NO];
}

//Do not call this directly if you are running on a background thread.
- (void) helperMethod{
  [[NSNotificationCenter defaultCenter] postNotificationName:@"SOMENAME" object:self];
}

不幸的是,这引入了发送方和接收方之间的微妙耦合,因为您正在修改发送者容纳接收者。

Unfortunately this introduces a subtle coupling between the sender and receiver in that you are modifying the sender to accommodate the receiver.

正如XJones指出的那样,一个更好的解决方案是让发送者在它决定的任何线程上发出通知,然后使监听器负责使用正确的线程来执行它需要的任何动作。

An even better solution, as XJones points out, is to have the sender send out the notification on whatever thread it decides to, and then to make the listener responsible for using the proper thread to perform whatever action it needs to.

希望这是有用的。

这篇关于是否可以使用通知回复到IOS应用程序的主线程? (cf performSelectorOnMainThread)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆