简体   繁体   中英

How to remove an observer for NSNotification in a UIView?

I've added an observer in a custom UIView I've created under 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. 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. 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. You can remove the view as an observer in dealloc , which will be called when the view is no longer retained by anyone:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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