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)

iOS development with Swift - book: https://manning.com/books/ios-development-with-swift video course: https://www.manning.com/livevideo/ios-development-with-swift-lv

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 comment