Cocoa Custom Notification Example

Objective CCocoaNotifications

Objective C Problem Overview


Can someone please show me an example of a Cocoa Obj-C object, with a custom notification, how to fire it, subscribe to it, and handle it?

Objective C Solutions


Solution 1 - Objective C

@implementation MyObject

// Posts a MyNotification message whenever called
- (void)notify {
  [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self];
}

// Prints a message whenever a MyNotification is received
- (void)handleNotification:(NSNotification*)note {
  NSLog(@"Got notified: %@", note);
}

@end

// somewhere else
MyObject *object = [[MyObject alloc] init];
// receive MyNotification events from any object
[[NSNotificationCenter defaultCenter] addObserver:object selector:@selector(handleNotification:) name:@"MyNotification" object:nil];
// create a notification
[object notify];

For more information, see the documentation for NSNotificationCenter.

Solution 2 - Objective C

Step 1:

//register to listen for event    
[[NSNotificationCenter defaultCenter]
  addObserver:self
  selector:@selector(eventHandler:)
  name:@"eventType"
  object:nil ];

//event handler when event occurs
-(void)eventHandler: (NSNotification *) notification
{
    NSLog(@"event triggered");
}

Step 2:

//trigger event
[[NSNotificationCenter defaultCenter]
    postNotificationName:@"eventType"
    object:nil ];

Solution 3 - Objective C

Make sure to unregister notification (observer) when your object is deallocated. Apple documentation states: "Before an object that is observing notifications is deallocated, it must tell the notification center to stop sending it notifications".

For Local Notifications the next code is applicable:

[[NSNotificationCenter defaultCenter] removeObserver:self];

And for observers of distributed notifications:

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmattdwenView Question on Stackoverflow
Solution 1 - Objective CJason CocoView Answer on Stackoverflow
Solution 2 - Objective CmracokerView Answer on Stackoverflow
Solution 3 - Objective CGrigori A.View Answer on Stackoverflow