ConfusedDeer
ConfusedDeer

Reputation: 3415

How do I call multiple methods in @selector for notification?

Currently I'm only calling one method when application will enter foreground. How do I call various methods in @selector?

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(displayHappyFace)
                                             name:UIApplicationWillEnterForegroundNotification
                                           object:nil];

Upvotes: 1

Views: 980

Answers (3)

uchuugaka
uchuugaka

Reputation: 12782

You can only put one selector there. Best practice is to create a new method called handleNotificationName: for each notification.

Example:

- (void)handleUIApplicationWillEnterForegroundNotification:(NSNotification *)aUIApplicationWillEnterForegroundNotification { }

This makes it really easy to figure out where your app handles each notification and makes code maintenance easy.

Inside the handler method you can call whatever methods you need to. You can have conditional logic also based on state you have or based the userInfo dictionary of the Notification ( if it has one ).

Don't forget to remove your notification observer in you object's dealloc method (at least, if not somewhere else because you might not want to always receive the notification depending on the use case)

Upvotes: 0

tipycalFlow
tipycalFlow

Reputation: 7644

Add another observer to UIApplicationWillEnterForegroundNotification if you wish to keep the methods' logic separate:

[[NSNotificationCenter defaultCenter] addObserver:self
                                     selector:@selector(displayHappyFace)
                                         name:UIApplicationWillEnterForegroundNotification
                                       object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
                                     selector:@selector(callOtherMethod)
                                         name:UIApplicationWillEnterForegroundNotification
                                       object:nil];

@selector supports only one method. Remember to remove self as the observer before releasing its memory, to avoid messages being passed to a nil object.

Upvotes: 1

Rajneesh071
Rajneesh071

Reputation: 31083

Just create a separate function for all your other function.

[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(AllFunction)
                                             name:UIApplicationWillEnterForegroundNotification
                                           object:nil];

All functions.

-(void) AllFunction
{
    [self displayHappyFace];
    [self otherFunction];
}

Upvotes: 2

Related Questions