Use NSNotificationCenter selector for one observer in multiple view controllers

隐身守侯 提交于 2020-01-22 02:08:51

问题


Can I use the selector getUpdate: in multiple view controllers? I'm registering my LevelViewController as an observer for both GameViewController and WinViewController. The latter 2 view controllers both have a back button (which, when pressed, pops you back to LevelVC), and the idea with the notification is to tell LevelVC whether or not to update the collection view cells (via the viewWillAppear: method) when the back button is pressed.

In viewWillAppear:, I wouldn't want to call two separate methods (one from GameVC and one from WinVC) in order to get my update, I just one fluid method that can be used in either.

Here's what I intend (in LevelVC):

- (void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(getUpdate:)        
                                                 name:@"getUpdateForCell" 
                                               object:nil];
}

And incorporate

- (void)getUpdate:(NSNotification *)notification {
    NSDictionary *data = [notification userInfo];
    // pop
}

twice...once in GameVC, and the other in WinVC.

Is this possible? Or should I just make two separate notifications?


回答1:


You can create your own NSDictionary and pass as a value in userInfo to determine which UIViewController you came from and appropriately handle the situation using an if statement.

Alternatively

You can use delegates to execute an event when the back button is present and perform appropriate actions on the previous UIViewController. Personally i prefer the this approach.



来源:https://stackoverflow.com/questions/40700827/use-nsnotificationcenter-selector-for-one-observer-in-multiple-view-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!