简体   繁体   中英

Add & Post 'NSNotificationCenter' in the Same Class

Is there a way to add an observer in a Class other than the one where the method is? Something I can add globally.

I have tried something like this below, but it doesn't work. Please advice a method to do so? This is in HomeVC.m, I'm also posting the notification from this class.

UIStoryboard *storybrd = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
HomeViewController *controller =[storybrd instantiateViewControllerWithIdentifier:@"VC123"];

[[NSNotificationCenter defaultCenter] addObserver:controller selector:@selector(somethingHappens:) name:@"notificationName" object:nil];

This method is in VC123.m

-(void) somethingHappens:(NSNotification*) notification { }

When you do:

HomeViewController *controller =[storybrd instantiateViewControllerWithIdentifier:@"VC123"];

You get a new instance of the controller. If it's the first time and you keep that instance and reuse it then that's fine. But what you're probably doing is not keeping it so it's getting destroyed. That would usually result in a crash (unless the controller is removing itself as an observer before it's destroyed, which it should).

You can add any instance as an observer, it doesn't need to be from within the class specifically, you just need an instance of it - and that instance should be the existing one, not a new one that you just created.

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