iphone - 如何阻止 NSNotification 中的观察者调用两次?

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

我搜索了它,但没有找到解决方案。

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

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

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

最佳答案

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

解决方案 2: 即使只发布一次通知,action 也会被调用多次,因为您为通知添加了观察者(无论通知是否相同)。例如,以下两行将为同一个通知(aSelector)注册观察者(self)两次。

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

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

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

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

https://stackoverflow.com/questions/7751191/

相关文章:

objective-c - Xcode 在 iOS 8 的 Main() 中抛出异常,断点为 'al

objective-c - iOS 8 Mapkit Objc 无法获取用户位置

objective-c - Objective-C 中的简单 http post 示例?

objective-c - 从 NSMutableString 中删除最后一个字符

objective-c - 可变集合有文字语法吗?

ios - 缩放 UIView 及其所有子项

ios - 如何调整 UITableView 中原型(prototype)单元格的左边距?

iphone - 以流畅的动画显示/隐藏导航栏

objective-c - 如何在 Objective-C 中使用自定义委托(delegate)

objective-c - 对 NSTimer 目标的弱引用以防止保留循环