NSNotificationCenter Tutorial

So I come from a Flash background (I know, I know) and one of the things I really like about coding in AS3 is the event based system. AS3 allows custom events that bubble through the hierarchy of objects and only those objects listening to the event need respond. It’s very elegant solution that conforms to the autonomy of classes in OOP design.
Obj C has a similar solution, or at least I use it in a similar way. It’s called NSNotification and we use the NSNotifictionCenter to add observers to listen for notifications. Notifications essentially being events and the NSNotificationCenter is a singleton object that manages all the Notifications.

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"view did load");
	// Do any additional setup after loading the view, typically from a nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shitWorkedBitches) name:@"myEventBitches" object:nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myEventBitches" object:nil];
}

-(void)shitWorkedBitches{
    //[[ NSNotificationCenter defaultCenter]removeObject:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"mySelector" object:nil];
    NSLog(@"Shit worked yo");
}  

There’s three important steps:
1. Create the observer to listen for the notification (event) to happen.
2. Post the notification when our event happens.
3. remove the observer when we no longer need it.

1.I’ve done everything in the viewDidLoad method.
Create the observer by adding “self” as the new observer, pass in a function name as the selector. Then pass in a string as the name of the notification the NotificationCenter listens for: @”myEventBitches”.
2. Post the notification by passing the notification name to the postNotificationName method.
3. Create the method we want to trigger, remove the observer and do something…

So there it is, quick and dirty.
What we’ve done here is create a custom notification. There are some other options that allow you to parse params and you’ll notice there are many internal notifications used by iOS frameworks, the MPMediaPlayer framework comes to mind.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *