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

查看:112
本文介绍了如何避免添加多个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 for目标/选择器,然后再添加它。我想象你可以添加这个类别方法:

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天全站免登陆