简体   繁体   English

如何在UIView中删除NSNotification的观察者?

[英]How to remove an observer for NSNotification in a UIView?

I've added an observer in a custom UIView I've created under initWithFrame: . 我在initWithFrame:下创建的自定义UIView中添加了一个观察者initWithFrame:

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

The problem is, this view is a subview. 问题是,这个视图是一个子视图。 When the view is loaded again, it calls the initWithFrame message again, thus adding two observers and so on. 再次加载视图时,它再次调用initWithFrame消息,从而添加两个观察者,依此类推。 How can I remove the observer when the view is going to disappear? 当视图消失时,如何移除观察者? Since it is a UIView , it says that viewWillDisappear:(BOOL)animated is not a valid method. 因为它是一个UIView ,它说viewWillDisappear:(BOOL)animated不是一个有效的方法。 Any ideas? 有任何想法吗?

You've said that initWithFrame: is being called more than once, so I assume this means that the view is being destroyed and recreated. 您已经说过initWithFrame:被多次调用,所以我认为这意味着视图正在被销毁并重新创建。 You can remove the view as an observer in dealloc , which will be called when the view is no longer retained by anyone: 您可以在dealloc删除视图作为观察者,当任何人不再保留视图时,将调用该视图:

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

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

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