如何避免添加多个 NSNotification 观察者? [英] How to avoid adding multiple NSNotification observer?

查看:21
本文介绍了如何避免添加多个 NSNotification 观察者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在 API 似乎没有提供一种方法来检测是否已经为特定的 NSNotification 添加了观察者.除了在您的一端维护一个标志以进行跟踪之外,避免添加多个 NSNotification 观察者的最佳方法是什么?有没有人已经创建了一个类别来促进这一点?

Right now the API doesn't seem to provide a way to detect if an observer has already been added for a particular NSNotification. What's the best way to avoid adding multiple NSNotification observers other than maintaining a flag on your end to keep track? Has anyone already created a category to facilitate this?

推荐答案

防止添加重复观察者的一种方法是在再次添加之前显式调用目标/选择器的 removeObserver.我想您可以将其添加为类别方法:

One way to prevent duplicate observers from being added is to explicitly call removeObserver for the target / selector before adding it again. I imagine you can add this as a category method:

@interface NSNotificationCenter (UniqueNotif)

- (void)addUniqueObserver:(id)observer selector:(SEL)selector name:(NSString *)name object:(id)object {

        [[NSNotificationCenter defaultCenter] removeObserver:observer name:name object:object];
        [[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:name object:object];

}

@end

这假设您只会为任何通知名称的每个目标添加一个唯一的观察者,因为它将删除该通知名称的所有现有观察者.

This assumes that the you will only add one unique observer to each target for any notification name, as it will remove any existing observers for that notification name.

这篇关于如何避免添加多个 NSNotification 观察者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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