Home > CodeSnippets, iOS, Objective-C > NSNotificationCenter – Custom events to implement Observer Pattern

NSNotificationCenter – Custom events to implement Observer Pattern

Here’s how it would look in Cocoa —

// Send a notification
[[NSNotificationCenter defaultCenter] postNotificationName:
   @"GotInformationsNotification" object:nil];

// Register an observer
[[NSNotificationCenter defaultCenter] addObserver:self
   selector:@selector(doSomething:) name:@"GotInformationsNotification"
   object:nil];

// Handle the notification
- (void) doSomething:(NSNotification*) notification {
   ...
}

// Remove an observer
[[NSNotificationCenter defaultCenter] removeObserver:self
   name:@"GotInformationsNotification" object:nil];
// Use the object attribute of the postNotificationName
// method to pass data/objects with your event
NSDictionary *userInfoDictionary = [NSDictionary dictionaryWithObject:
   @"the object" forKey:@"object"];
[[NSNotificationCenter defaultCenter] postNotificationName:
   @"GotInformationsNotification" object:self userInfo:userInfoDictionary];

// Handle the notification
- (void) doSomething:(NSNotification*) notification {
   //Get the content of the notification data
   NSDictionary *userInfo = [notification userInfo];
   if (userInfo != nil) {
      NSString* data = [userInfo objectForKey:@"object"];
   }
}

Here’s how it would look in AS3 —

View 1:

this.addEventListener("buttonClicked", gotoNextView);
...

View 2:

//..inside button click handler..
dispatchEvent(new Event("buttonClicked));

Advertisements
Categories: CodeSnippets, iOS, Objective-C
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: