Saturday, June 27, 2015

Using NSNotificationCenter in Swift

NSNotificationCenter is a convenient method to implement Observer pattern in iOS, something similar to what we say Signal/Slot in Qt framework.

To register one self as observer to some event, you can use addObserver method form NSNotificationCenter. In below code you are adding self as observer, selector is method which will be called when event is triggered, name is name of event or notification in which we are interested in, and object is object from which we want to receive event from, nil means we are ready to receive event from any object.
NSNotificationCenter.defaultCenter().addObserver(
    self, 
    selector: "gameViewClosed", 
    name: "gameViewClosed", 
    object: nil);
Now to trigger the notification, you can use postNotificationName method from NSNotificationCenter. Following code shows the same. Here we are sending notification for "gameViewClosed" event, object nil mean deliver event to all interested objects.
NSNotificationCenter.defaultCenter().postNotificationName(
    "gameViewClosed", 
    object: nil);
That's it, thanks for reading.

No comments:

Post a Comment