Graphics Programs Reference
In-Depth Information
Delegation
When you set the
delegate
property of the
CLLocationManager
and implemented
the two location-finding methods in
WhereamiViewController
, you were using a
design pattern called
delegation
. This is a very common pattern in Cocoa Touch, and many
classes have a
delegate
property.
Delegation is an object-oriented approach to
callbacks
. A callback is a function that is sup-
plied in advance of an event and is called every time the event occurs. Some objects need
to make a callback for more than one event. For instance, the location manager wants to
“callback” when it finds a new location and when it encounters an error.
However, there is no built-in way for two (or more) callback functions to coordinate and
share information. This is the problem addressed by delegation - we supply a single deleg-
ate to receive all of the event messages for a particular object. This delegate object can then
store, manipulate, act on, and relay the related information as it sees fit.
Let's compare delegation with another object-oriented approach to callbacks: target-action
pairs. You used target-action pairs with the
UIButton
s in your
Quiz
application from
when a particular event occurs (like a button tap). A new target-action pair must be created
for each distinct event (like a tap, a double tap, or a long press). With delegation, you set
the delegate once and then can send it messages for many different events. The delegate
will implement the methods that correspond to the events it wants to hear about (
Fig-
ure 4.7
).
Figure 4.7 Target-action vs. delegation