繁体   English   中英

如何删除另一个类中的noitification观察者?

[英]How to remove noitification observer in another class?

我在类A中创建了一个通知

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

我在类B中发布了这个带有名字的通知

    [[NSNotificationCenter defaultCenter]postNotificationName:@"ViewChanged" object:nil];

现在我想在C语言中删除此通知,如下所示。 可能吗? 因为我需要从class-c去A班。

     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ViewChanged" object:nil];
     [[NSNotificationCenter defaultCenter] removeObserver:nil name:@"ViewChanged" object:nil];
     [[NSNotificationCenter defaultCenter] removeObserver:self];

我试过但是通知没有删除和它的呼叫两次。 如何为NSNotificationCenter创建对象?

[[NSNotificationCenter defaultCenter] removeObserver:nil name:@"ViewChanged" object:nil];

您的代码无法正常工作,因为removeObserver的第一个参数是nil,如文档中所述。

- (void)removeObserver:(id)notificationObserver name:(NSString *)notificationName object:(id)notificationSender

notificationObserver

观察者从调度表中删除。 指定观察者以仅删除此观察者的条目。 不能为零,否则消息将无效。

可能的解决方案:

objectA可以侦听第二个通知,例如removeA 然后在objectA创建一个方法,将objectA作为ViewChanged的观察者移除。 removeA应该触发该方法。

objectC然后将只需要发布removeA通知, objectA将停止监听。

正如@Wain正确地说的那样,这是一种奇怪/错误的设计。 如果你真的想购买,你需要做:

[[NSNotificationCenter defaultCenter] removeObserver:objectA name:@"ViewChanged" object:nil];

因此,当您调用addObserver:时, objectA是您作为self传递的对象addObserver: 你现在需要将objectA转换为C类的实例,这表明你想要做的事情是错误/怪异的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM