这可能更像是一个关于 iOS 的 Objective-c 问题,但我已经看到了一些类似于以下的示例代码,我想更好地理解这些代码。
@interface MyMapView : MKMapView <MKMapViewDelegate> {
// ivars specific to derived class
}
@property(nonatomic,assign) id<MKMapViewDelegate> delegate;
@end
@implementation MyMapView
- (id) initWithFrameCGRect)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)mapViewMKMapView *)mapView regionWillChangeAnimatedBOOL)animated
{
if( [delegate respondsToSelectorselector(mapView:regionWillChangeAnimated] )
{
[delegate mapView:mapView regionWillChangeAnimated:animated];
}
}
@end
我的两个问题是: 1. 为什么要调用 super.delegate 并且只将“delegate”声明为属性? 2. 为什么要拦截所有的委托(delegate)调用,然后将它们转发回委托(delegate)?
感谢任何见解。
Apple 的文档明确指出您应该避免子类 MKMapView
:
Although you should not subclass the MKMapView class itself, you can get information about the map view’s behavior by providing a delegate object.
所以我猜这个委托(delegate)“前进”模式是用来不破坏事物的。
我对MKMapView
使用了一些不同的方法。为了尽量减少破损,我使用了两个类。一个子类 MKMapView
并且只是覆盖 init/dealloc 方法并将 delegate
属性分配/释放到另一个类的实例。另一个类是 NSObject
的子类,它实现了 MKMapViewDelegate
协议(protocol),将是真正的工作。
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)initWithMapViewReportsMapView *)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
MapDelegate
类的 mapView
属性不是严格需要的,但如果想要对 map View 执行不是某些 MKMapViewDelegate
方法调用、定时器等
关于iphone - MKMapViewDelegate 派生类和委托(delegate)赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7586961/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |