Use NSNotificationCenter selector for one observer

2019-03-05 00:50发布

问题:

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.