Graphics Programs Reference
In-Depth Information
Methods declared in a protocol can be required or optional. By default, protocol methods
are required. If a protocol has optional methods, these are preceded by the directive @op-
tional . Looking back at the CLLocationManagerDelegate protocol, you can see
that all of its methods are optional. This is typically true of delegate protocols.
Before sending an optional message, the object first asks its delegate if it is okay to send
that message by sending another message, respondsToSelector: . Every object im-
plements this method, which checks at runtime whether an object implements a given
method. You can turn a method selector into a value that you can pass as an argument
with the @selector() directive. For example, CLLocationManager could imple-
ment a method that looks like this:
- (void)finishedFindingLocation:(CLLocation *)newLocation
{
// locationManager:didUpdateToLocation:fromLocation:
// is an optional method, so we check first.
SEL updateMethod = @selector(locationManager:didUpdateToLocation:fromLocation:);
if ([[self delegate] respondsToSelector:updateMethod]) {
// If the method is implemented, then we send the message.
[[self delegate] locationManager:self
didUpdateToLocation:newLocation
fromLocation:oldLocation];
}
}
If a method in a protocol is required, then the message will be sent without checking first.
This means that if the delegate does not implement that method, an unrecognized selector
exception will be thrown, and the application will crash.
To prevent this from happening, the compiler will insist that a class implement the re-
quired methods in a protocol. But, for the compiler to know to check for implementations
of a protocol's required methods, the class must explicitly state that it conforms to a pro-
tocol. This is done in the class header file: the protocols that a class conforms to are added
to a comma-delimited list inside angled brackets in the interface declaration following the
superclass.
In WhereamiViewController.h , declare that WhereamiViewController con-
forms to the CLLocationManagerDelegate protocol.
@interface WhereamiViewController : UIViewController <CLLocationManagerDelegate>
Build the application again. Now that you've declared that WhereamiViewControl-
ler conforms to the CLLocationManagerDelegate protocol, the warning from the
Search WWH ::




Custom Search