Graphics Programs Reference
In-Depth Information
view controllers in a navigation controller stack, but one of them is interested in what is
going on in the other. Instead of giving them pointers to each other, which can be messy
for a variety of reasons, one of view controllers can post notifications to the notification
center. The other could register as an observer for that type of notification. Similarly, an-
other view controller could come along and register for the same notification, and both
observers would get updated.
Blocks are the outliers when it comes to callbacks because they are not an object-oriented
approach. Blocks are useful when the callback is going to happen only once or when the
callback is just a quick and simple task (like updating a progress bar).
One of the reasons blocks are better suited for this one-shot behavior is that they will take
ownership of any object they reference. If a block was to stay around forever, the objects
it references would also stay around forever. Of course, you can destroy the block when it
is no longer needed, but what if that block is owned by an object that the block referen-
ces? The object owns the block, the block owns the object, and now you can't destroy
them without some extra work. Since blocks stick around for just the one event, they will
own what they need until they no longer need it.
Another reason blocks are well-suited for this situation goes along with the reason why
they are good for quick and simple tasks: you can define the block's code at the same
point where the block is registered as a callback. This keeps your code nice and clean.
An approach to callbacks we have not discussed is subclassing. In some languages, deleg-
ation is not feasible because of the structure of the language. In these languages, classes
like CLLocationManager would be abstract classes - ones that were meant to be sub-
classed. Any time you wanted to use an instance of CLLocationManager , you would
subclass it and write the code for what happens when an event occurs in the implementa-
tion of this subclass. The subclass would probably have an instance variable for the object
it was going to tell about these events, and that object would declare and define these
methods. This gets complicated and ugly pretty quickly, and in Cocoa Touch, you do not
see this pattern because we have better alternatives.
Search WWH ::




Custom Search