NSNotification removeObserver问题

12

我可能是脑残或者对于NSNotificationCenter的理解不够深入。

问题在于,如果我创建了一个观察者,并在下一行尝试像这样删除它:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllVisibleMapViews) name:@"ClearVisibleMaps" object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"ClearVisibleMaps"];

我获得

*** Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer <MyApp 0x592db70> for the key path "ClearVisibleMaps" from <NSNotificationCenter 0x4e0fbb0> because it is not registered as an observer.'

我逐行添加和删除观察者,只是为了说明一点。在我的代码中,我将在dealloc中使用remove。

那么,有什么想法可以解释它为什么会告诉我一开始没有添加观察者吗?

1个回答

24

你正在移除keypath的观察者,而不是通知名称。移除应该像这样:

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

1
谢谢,所以我是脑残了吗 :-) 嘿嘿,至少今天是这样。 - Cyprian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接