One thing I use quite a bit in my Actionscript projects are Events. It requires no coupling whatsoever, and is very modular. In iOS, these events are known as Notifications, and work almost the same way.
To send a message in Objective-C, use the following:
The first part uses the built-in notification handler that is part of the Cocoa framework. Unless you need more than one handler, you probably should use this. The ‘observer’ is the object that will handle the notification. Set it to self if the object that contains this snippet is to execute the callback, and set it to another object if you want that to handle it. In Actionscript, you would assign a listener to another object by typing something like “myObjectInstance.myCallbackMethod.” The selector: parameter is a bit tricky. This specifies the signature of the method that is to be called. One thing you really should get into the habit of doing is structuring your callback method to take in a parameter of type NSNotification, as follows:
MAKE SURE YOU PUT THE COLON INSIDE THE SELECTOR!!! If its not there, it will most likely fail silently, which really sucks. I wasted way too much time figuring this out.
The name field is the NSString identifier of the notification, similar to the Event type in AS. Best practices dictates that this should be in a constant.
Finally, the object field is there should you want to append any data to this notification, just like the “data” property of AS events. If not, just leave it null.
Here’s how to send an event/notification:
The only thing you’ll need to change is the postNotificationName: element which is the same as the AS type, as mentioned above. Finally, the object: parameter is where you append any data, should you need it.
You can add and remove observers as needed, but watch out for memory leaks, or each and every object that has an observer for your note will respond whether you like it or not!