Question

I want to register a notification observer outside of the class that is observing the notification reception.

i tried to do it like this :

[[NSNotificationCenter defaultCenter] 
       addObserver:[ViewController class]  
       selector:@selector(NotificationReceived:) 
       name:@"notification" object:nil];

however, this forces me to make the method NotificationReceived in ViewController class to be +(void) instead of -(void) like i want it to be

is there a way to register the ViewController as a notification observer outside the ViewController class ?

Was it helpful?

Solution

You have to create an instance of that class and keep it alive in memory, something like:

UIViewController *myViewController = [[UIViewController alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:myViewController
                                         selector:@selector(NotificationReceived:)
                                             name:@"notification"
                                           object:nil];

And remember to un-register observer before the observer is deallocated, else your app will crash

Or in Swift 3:

let myViewController = UIViewController()
NotificationCenter.default.addObserver(
    myViewController,
    selector: #selector(NotificationReceived),
    name: Notification.Name("notification"),
    object: nil)

OTHER TIPS

For Posting notification:

 [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:nil];

For adding observer in any view:

 // Add observer
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourmethod) name:@"notificationName" object:nil];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top