与iOS相比,这可能更像是一个objective-c问题,但我已经看到了一些类似于下面的示例代码,我想更好地理解它们。
@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.为什么拦截所有的委托调用,只是将它们转发回委托?
我很感谢你的见解。
发布于 2011-09-29 03:04:19
苹果公司的文档明确指出,您应该避免使用子类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属性分配/释放给另一个类的一个实例。另一个类是实现MKMapViewDelegate协议的NSObject的子类,它将执行实际的工作。
MyMapView.h
@interface MyMapView : MKMapView
@endMyMapView.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];
}
@endMapDelegate类的mapView属性并不是严格需要的,但如果想要对映射视图做一些事情,而这不是某些MKMapViewDelegate方法调用、计时器等的结果,那么它可能会很有用。
发布于 2011-09-29 02:12:50
希望它能解决这个问题。
https://stackoverflow.com/questions/7586961
复制相似问题