Frage

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 ?

War es hilfreich?

Lösung 2

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
                                                  }];

Andere Tipps

Just to let you know that exist this method:

[[NSNotificationCenter defaultCenter] addObserverForName:@"ready" 
                                                  object:nil 
                                                   queue:nil 
                                              usingBlock:^(NSNotification *note) {
    //Do something
}];

and also that you are talking about write a function or a block in a @selector directive...doesn't make sense and is not possible.

Enjoy the function above ;)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top