Custom Events in Objective-C

2nd March 2009

If you are living in the ActionScript world and you are looking for something like an event handling system, you might won’t find any. I googled events and custom events, callbacks and finally figured out that they call it “Notifications”.

Events or in this case Notifications are used for having loosely coupled relationships between instances in your application. So it is possible to let other instances listen to specific events without knowing each other.

If you want to listen to a custom event in ActionScript it would look something like this:

instance.addEventListener("eventType", eventHandler);

function eventHandler(e:Event)
{
    trace("event triggered");
}

In your instance you would trigger the event like this:

dispatchEvent( new Event("eventType") );

The Objective-C approach to listen to a Notification looks like this:

[[NSNotificationCenter defaultCenter]
    addObserver:self
    selector:@selector(eventHandler:)
    name:@"eventType"
    object:nil ];

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

The funny thing is that you don’t need to put this Event Listener on an instance. It just listens to the eventtype and as far as I understood you can trigger this event wherever you want. This makes it even more loosely coupled than the instance.addEventListener(); approach.

The “NSNotificationCenter” is something like a Singleton which is one unique Class that manages your events in your application.

And this is how you dispatch or trigger the event:

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

That’s it. Actually I like the approach in Objective-C even if it is more to write it is pretty easy to read.

Share this post:
  • Facebook
  • Twitter
  • del.icio.us
  • email
  • Print
  1. Excellent! I knew there was a way for Flash developers to learn Obj-C! thanks for the great post!

  2. Can you dispatch an event from any class? like a NSObject? because I am dispatch ing from a class to the application delegate and I get nothing?

  3. Thanks a lot!
    Tried to find this solution in many books, forums and so on during a couple of days!

    Thanks again!

  4. I knew handling shared data through the app delegate was a no-no and after I couldn’t get delegation to work (plus it was overkill). Notifications were my goal, this made is super simple, thanks! Rob

  5. hi i have used this code in my application…….this is realy helpful for me. thanks

  6. Thanks for this, quick, concise and works like a charm!

  7. Thanks for this clear comparison. Objective-c is not always easy coming from an as2/3 background!

    keep it up man!

  8. Thanks Raphael, that’s a great tip :)

Leave a Message