This is probably more of an objective-c question over iOS but I’ve seen some example code similar to the following that I’d like to better understand.
@interface MyMapView : MKMapView <MKMapViewDelegate> {
// ivars specific to derived class
}
@property(nonatomic,assign) id<MKMapViewDelegate> delegate;
@end
@implementation MyMapView
- (id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// initialize the ivars specific to this class
// Q1: Why invoke super on this delegate that's also a property of this class?
super.delegate = self;
zoomLevel = self.visibleMapRect.size.width * self.visibleMapRect.size.height;
}
return self;
}
#pragma mark - MKMapViewDelegate methods
// Q2: Why intercept these callbacks, only to invoke the delegate?
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
if( [delegate respondsToSelector:@selector(mapView:regionWillChangeAnimated:)] )
{
[delegate mapView:mapView regionWillChangeAnimated:animated];
}
}
@end
My two questions are:
1. Why would one invoke the super.delegate and also only declare the ‘delegate’ as a property?
2. Why intercept all of the delegate calls only to forward them back to the delegate?
I appreciate any insights.
Apple’s documentation explicitly states that you should avoid subclass
MKMapView:http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKMapView_Class/MKMapView/MKMapView.html#//apple_ref/doc/uid/TP40008205
So i guess this delegate “forward” pattern is used to not break things.
I use a little different approach to subclass
MKMapView. To minimize breakage i use two classes. One that subclassMKMapViewand just override the init/dealloc method and assign/release thedelegateproperty to a instance of the other class. The other class is a subclass ofNSObjectthat implements theMKMapViewDelegateprotocol and will be the one that does the real work.MyMapView.h
MyMapView.m
The
mapViewproperty forMapDelegateclass is not strictly needed but is probably useful if want to do things to the map view that that is not a result of someMKMapViewDelegatemethod call, timers etc.