Objective c 删除可能不存在的NSNotification observer

Objective c 删除可能不存在的NSNotification observer,objective-c,nsnotificationcenter,Objective C,Nsnotificationcenter,关于这个问题,我似乎找不到明确的答案 删除可能不存在的观察者可以吗 示例代码: -(void)commonInit{ [[NSNotificationCenter defaultCenter]removeObserver:self]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(userDidC

关于这个问题,我似乎找不到明确的答案

删除可能不存在的观察者可以吗

示例代码:

-(void)commonInit{

    [[NSNotificationCenter defaultCenter]removeObserver:self];


    [[NSNotificationCenter defaultCenter]addObserver:self
                                        selector:@selector(userDidChangePrecision:)
                                            name:kUser_Changed_Precision
                                          object:nil];

 } 


-(void)dealloc{

    [[NSNotificationCenter defaultCenter]removeObserver:self];

    [super dealloc];

}

这将防止在对象可能在运行时重新初始化的情况下为该对象初始化多个观察者。

来自Apple文档的代码片段:

- (void)removeObserver:(id)notificationObserver
    Parameters
    *notificationObserver*
        The observer to remove. Must not be nil.

- (void)removeObserver:(id)notificationObserver name:(NSString *)notificationName object:(id)notificationSender
    Parameters
    *notificationObserver*
        Observer to remove from the dispatch table. Specify an observer to remove only entries for this observer. Must not be nil, or message will have no effect.
在这两种情况下,警告观察员不得为零被夸大;在这两种情况下,效果都是此消息无效。既没有编译器错误,也没有运行时错误,没有僵尸,&c

同样,指定一个没有观察的观察者也没有效果

不是一个明确的答案,而是基于对尝试和错误代码的观察和调查,例如:

[[NSNotificationCenter defaultCenter]removeObserver:nil];

[[NSNotificationCenter defaultCenter]removeObserver:[UIView new]]

我找不到关于是否允许删除不存在的观察者的最终文档,但我认为可以通过这种方式阅读
NSNotificationCenter
文档。它表示
removeObserver:name:object:
删除匹配的观察者。我只是假设这不包括匹配的观察者

但您的方法可能有害的另一个原因是:当调用
commonInit
方法时,其他代码(子类或超类的init)可能已经注册到通知。当子类化
UIViewController
时,甚至可能会出现这种情况(针对内存警告)


所以我想说,你永远不应该无条件地从通知中心注销,除非是在dealloc中。

你可以在你的潜在观察员中添加一个标志。。如果不是代码中定义的类,则可以通过category+objc_[set | get]Associated对象添加它。@nielsbot,这很好。很有可能假设它没问题?@Miek我对你完全陌生,但我关心我的项目,如果我们是结对编程,我会告诉你这没问题;但可以肯定的是,这并不是你想要的确切答案。多次给commonInit打电话似乎很奇怪?