stktrc
stktrc

Reputation: 1639

Using a NSNotification as an if argument

Just wondering if there is a way to use a NSNotification observer as an if statement argument, or to have a block of code in your selector section

EG

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector( { SOME NEW CODE GOES HERE! ) name:@"addressTypeChanged" object:nil];

OR

if ([[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(self) name:@"addressTypeChanged" object:nil]) {

//some code//
}

Upvotes: 0

Views: 107

Answers (2)

Jessedc
Jessedc

Reputation: 12460

To your first line: No, there's no way to place a block within @selector(). It might be worth taking a look around at what @selector is and how it works. Here's one particular question that might put you on the right track.

To your second line: The addObserver:selector:... method has a void return type and would always equate to NO inside an if statement.

What you might be looking for is the NSNotificationCenter block based API:

- (id)addObserverForName:(NSString *)name 
                  object:(id)obj 
                   queue:(NSOperationQueue *)queue 
              usingBlock:(void (^)(NSNotification *))block

The block parameter will be called when the notification is received.

Upvotes: 2

Sunny Shah
Sunny Shah

Reputation: 13020

[[NSNotificationCenter defaultCenter] addObserverForName:@"addressTypeChanged"
                                                  object:object
                                                   queue:nil
                                              usingBlock:^(NSNotification *notification){
                                                  /*
                                                    here you can call another methos
                                                   */
                                              }];

Upvotes: 0

Related Questions