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

sud*_*-rf 7 iphone cocoa-touch objective-c nsnotifications uiview

我在我创建的自定义UIView中添加了一个观察者initWithFrame:.

[[NSNotificationCenter defaultCenter] addObserver:self 
         selector:@selector(updateZipFromLocation:) 
          name:@"zipFoundFromLocation" 
           object:nil];
Run Code Online (Sandbox Code Playgroud)

问题是,这个视图是一个子视图.再次加载视图时,它再次调用initWithFrame消息,从而添加两个观察者,依此类推.当视图消失时,如何删除观察者?因为它是a UIView,它说这viewWillDisappear:(BOOL)animated不是一个有效的方法.有任何想法吗?

Jus*_*ers 12

你已经说过initWithFrame:不止一次被调用,所以我认为这意味着视图正在被破坏和重新创建.您可以将视图作为观察者移除dealloc,当任何人不再保留视图时,将调用该视图:

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}
Run Code Online (Sandbox Code Playgroud)