如何阻止NSNotification中的Observer调用两次? [英] How to stop the Observer in NSNotification to called twice?

查看:85
本文介绍了如何阻止NSNotification中的Observer调用两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSNotification 的观察者,它被调用两次。我不知道该怎么做。

I have an observer of NSNotification which is called twice. I do not know what to do with it.

我用谷歌搜索但没有找到解决方案。

I googled it but no solution found.

[[NSNotificationCenter defaultCenter] addObserver:self
     selector:@selector(connectedToServer:) name:@"ConnectedToServer" object:nil];

- (void)connectedToServer:(NSNotification*)notification {

    [[NSNotificationCenter defaultCenter] postNotificationName:@"SendMessageToServer" object:message];
}


推荐答案

解决方案1: 首先要检查通知本身是否发布两次。

Solution 1: The first thing is to check if the notification itself is posted twice.

解决方案2:即使通知仅发布一次, action 将被多次调用,你已经添加了通知的观察者(无论通知是否相同)。例如,以下两行将为同一通知( aSelector )注册观察者( self )两次。 / p>

Solution 2: Even if the notification is posted only once, the action will be called as many times you've added the observer for the notification (no matter the notification is same or not). For example, the following two lines will register the observer(self) for the same notification(aSelector) twice.

[[NSNotificationCenter defaultCenter] addObserver:self selector:aSelector name:aName object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:aSelector name:aName object:nil];

您必须找到第二次添加观察者的位置,然后将其删除。并且还要确保您添加观察者的代码不会被调用两次。

You have to find where you are adding observer for the second time, and remove it. And also make sure that the code where you are add the observer is not called twice.

解决方案3:如果您不确定是否已经添加了观察者,您可以简单地执行以下操作。这将确保观察者只被添加一次。

Solution 3: If you are not sure whether you have already added the observer or not, you can simply do the following. This will make sure that the observer is added only once.

[[NSNotificationCenter defaultCenter] removeObserver:self name:aName object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:aSelector name:aName object:nil];

这篇关于如何阻止NSNotification中的Observer调用两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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