COMMUNICATION BETWEEN OBJECTS IN OBJECTIVE C AND SWIFT COMPARED WITH ACTIONSCRIPT – PART 5

Events

Well, this is the final blog post in the series of communication between objects and for something familiar, events are available in Objective C and Swift too. The equivalent of ActionScript’s EventDispatcher is called NSNotificationCenter. Rather than each display object inheriting the EventDispatcher, the NSNotificationCenter is more like a central hub where notifications pass through.

The terminology in AS [event, dispatch, listener] becomes in ObjC/Swift [notification, post, observer].

Dispatch Event/Post Notification:

ActionScript3:

this.dispatchEvent(new Event(“SomeEvent”));

Objective C:

[[NSNotificationCenter defaultCenter] postNotificationName:@"SomeNotification" object:self];

Swift:

NSNotificationCenter.defaultCenter().postNotificationName("SomeNotification" object:self)

Listen for Event/Observe Notification:

ActionScript3:

this.addEventListener(“SomeEvent”,someListener);
function someListener(event:Event):void {
 // handle event here
}

Objective C:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someObserver:) name:@"SomeNotification" object:nil];
- (void)someObserver:(NSNotification *)notification {
 // handle event here
}

Swift:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "someObserver:", name: SomeNotification, object: nil)
func someObserver(sender: AnyObject) {
}

Remove Event/Remove Observation:

ActionScript3:

this.removeEventListener(“SomeEvent”,someListener);

Objective C:

[[NSNotificationCenter defaultCenter] removeObserver:self name:@”SomeNotification” object:nil];
//alternatively you can remove all observers on this object:
[[NSNotificationCenter defaultCenter] removeObserver:self];

Swift:

NSNotificationCenter.defaultCenter().removeObserver(self name: SomeNotification, object: nil)
//alternatively you can remove all observers on this object:
NSNotificationCenter.defaultCenter().removeObserver(self)

Interactive developer, Author - iOS development with Swift - book coming 2017 https://manning.com/books/ios-development-with-swift

Tagged with:
Posted in Flash, Objective C, Swift
One comment on “COMMUNICATION BETWEEN OBJECTS IN OBJECTIVE C AND SWIFT COMPARED WITH ACTIONSCRIPT – PART 5
  1. […] 2: Actions Part 3: Delegates Part 4: Blocks/Closures And then in Part 5 I’ll come back to talk about our familiar friend […]

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: