Search code examples
iosnsnotificationcenter

ios notification, define handler function directly


I want to do some actions when receiving "ready" notification.

Basically, we do :

// earlier in a method
    ...
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector( notificationHandler )
     name:@"ready"
     object:nil];


// later in file
- (X) notificationHandler{
    ...
}

In my case, the method which will handle the notification will be an one-line standing function, so if possible, I would like to define it right in the observer block.

[[NSNotificationCenter defaultCenter]
 addObserver:self
 selector:@selector( I WANT TO DEFINE A FUNCTION HERE )
 name:@"ready"
 object:nil];

Any idea ?


Solution

  • Even if there are some official APIs to do this, I strongly suggest you to NOT use them, cause they're leaked. You can use FXNotifications from Nick Lockwood, which provides the feature you want: use a block as notification listener.

    Add the .h & .m files inside your project and then call:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                              forName:@"ready"
                                               object:nil
                                                queue:[NSOperationQueue mainQueue]
                                           usingBlock:^(NSNotification *note, id observer) {
                                                           // Your inline function here
                                                      }];