2011-09-28 140 views
2

這可能更多的是iOS上的objective-c問題,但我已經看到了一些類似於下面的代碼,我想更好地理解它。MKMapViewDelegate派生類和委託分配

@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 

我的兩個問題是:1。 一個爲什麼會調用super.delegate,也只有宣佈「代理」的財產? 2.爲什麼只攔截所有的委託來電轉回委託?

我很欣賞任何見解。

回答

2

蘋果的文件明確規定,你應該避免子類MKMapView

http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKMapView_Class/MKMapView/MKMapView.html#//apple_ref/doc/uid/TP40008205

雖然你不應該子類的MKMapView類本身,你可以 通過提供委託獲取關於地圖視圖的行爲信息 對象。

所以我想這個代表「向前」模式是用來不破壞的東西。

我對子類MKMapView使用了一些不同的方法。爲了儘量減少破損我使用兩個類。一個子類MKMapView,只是覆蓋init/dealloc方法,並將delegate屬性分配給其他類的實例。另一個類是NSObject的子類,它實現MKMapViewDelegate協議,並將成爲真正的工作。

MyMapView.h

@interface MyMapView : MKMapView 
@end 

MyMapView.m

// private map delegate class 
@interface MapDelegate : NSObject <MKMapViewDelegate> 
// instance is not alive longer then MKMapView so use assign to also solve 
// problem with circular retain 
@property(nonatomic, assign) MKMapView *mapView; 
@end 

@implementation MapDelegate 
@synthesize mapView; 

- (id)initWithMapView:(ReportsMapView *)aMapView { 
    self = [super init]; 
    if (self == nil) { 
    return nil; 
    } 

    self.mapView = aMapView; 

    return self; 
} 

// MKMapViewDelegate methods and other stuff goes here 

@end 

@implementation MyMapView 
- (id)init { 
    self = [super init]; 
    if (self == nil) { 
    return nil; 
    } 

    // delegate is a assign property 
    self.delegate = [[MapDelegate alloc] initWithMapView:self]; 

    return self; 
} 

- (void)dealloc { 
    ((MapDelegate *)self.delegate).mapView = nil; 
    [self.delegate release]; 
    self.delegate = nil; 

    [super dealloc]; 
} 
@end 

並不是必需的mapView屬性MapDelegate類,但可能是有用的,如果想要做的事情,以地圖視圖這是不是某些MKMapViewDelegate方法調用,定時器等的結果。

1
  1. 爲什麼要調用super.delegate並且只聲明'delegate'作爲屬性? Ans。由於您正在製作自定義的mapview,因此調用委託也很重要。我們正在調用超級委託來從自定義Mapview發送控件。

  2. 爲什麼攔截所有的委託調用只是將它們轉發給委託? Ans.在那行代碼中,我們將控件發送回在超類中聲明的委託方法來執行一些有用的事情。

希望它能解決查詢。