我正在向UITableViewHeader添加按钮,但在取消分配之前获取未删除观察者的控制台消息:
UIButton类的实例0x4b4750在键值时被释放 观察员仍在注册
这是可以理解的,所以我试图删除它们但不确定最好的方法来解决这个问题。想到的唯一事情是将它们全部添加到数组中,然后在dealloc中循环遍历它们并删除创建它们的类作为观察者。我不完全确定哪些参数传递到[[NSNotificationCenter defaultCenter] removeObserver
。每个标题视图中有三个不同的按钮,每个按钮触发不同的回调。这是否意味着我需要三个数组,对于所调用的每种操作类型,然后使用removeTarget
?
答案 0 :(得分:0)
来自docs:
重要通知中心不会保留其观察员, 因此,您必须确保取消注册观察者(使用 removeObserver:或removeObserver:name:object :)之前 释放。 (如果不这样做,则会产生运行时错误 center向已释放的对象发送消息。)
如果您已经将按钮子类化,那么您可以向所有观察者发布一条消息,表明可观察的UIButton即将消失。
[[NSNotificationCenter defaultCenter] postNotificationName:@"UIButton_dealloc" object:self];
或者,在分配按钮的类中,一旦删除按钮,您可以:
[[NSNotificationCenter defaultCenter] postNotificationName:@"UIButton_dealloc" object:theButton];
在这两种情况下,观察者对象都会这样做:
// The special event
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) name:@"UIButton_event" object:theButton];
// The dealloc
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopObserving:) name:@"UIButton_dealloc" object:theButton];
....
-(void) stopObserving:(NSNotification*)notif {
if ([name isEqualToString:@"UIButton_dealloc"]) {
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIButton_event" object:object];
}
}
然而,在UIButton的情况下,这是一个有点复杂的例子,但对其他情况可能有用。