【发布时间】:2012-09-07 02:46:02
【问题描述】:
为 MapKit 设置单独的委托类的正确方法是什么?
我有 MapView 类子类化 MKMapView 和符合 MKMapViewDelegate 协议的裸 MapDelegate 类只有一个初始化方法。
这是我使用的 MapView 初始化方法的摘录:
# MapView.m ...
@implementation MapView
- (id) initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// [self setShowsUserLocation:YES];
[self setDelegate:[[MapDelegate alloc] initWithMapView:self]];
MapDelegate 类唯一的方法是
# MapDelegate.m ...
- (id)initWithMapView:(MapView *)aMapView {
self = [super init];
self.mapView = aMapView;
return self;
}
有 [self setShowsUserLocation:YES]; 评论,一切正常 - 我看到了地图。如果我取消注释此行,我的应用程序开始崩溃。
我的 MapDelegate 类缺少什么?
更新 1:如果我不使用单独的类 MapDelegate 并仅设置 setDelegate:self - 一切正常。
更新 2:现在我明白了,[self setDelegate:[[MapDelegate alloc] initWithMapView:self]]; 字符串的问题是我需要 MapDelegate 类的寿命比现在长(委托属性具有 weak 属性)。如果我执行以下操作:
@property (strong) id delegateContainer;
....
[self setDelegateContainer:[[MapDelegate alloc] init]];
[self setDelegate:self.delegateContainer];
...有效!有没有更好的方法来保留 MapDelegate 生命周期以及 MKMapView 的生命周期?
谢谢!
【问题讨论】:
标签: objective-c ios mkmapview mapkit