0

我制作了一个自定义的 MKAnnotation 类 MapLocation。我在设置或获取属性时没有遇到任何问题,除了在此方法中创建 MKAnnotationView。我需要在此处执行此操作,因为它应该从注释的索引中查找位置类型,并为 annotationView 选择一系列自定义注释图像中的一个。

在多次尝试在 MapLocation.h 和 .m 中设置自定义 getter 和 setter 之后,我将其归结为我什至无法复制(强制性)getter、标题,将其重命名为 title2,并尝试获取其返回值. 这是我的代码:

-(MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {
static NSString *placemarkIdentifier=@"Map Location Identifier";
NSString *str1=annotation.title;
NSString *str2=annotation.title2;
if([annotation isKindOfClass:[MapLocation class]]) {
    MKAnnotationView *annotationView=(MKAnnotationView *)[theMapView dequeueReusableAnnotationViewWithIdentifier:placemarkIdentifier];
    if (annotationView==nil) {
        annotationView=[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:placemarkIdentifier];
    }
    else
        annotationView.annotation=annotation;


    return annotationView;
}
return nil;

}

在第 4 行,正确返回了 title,但是第 5 行对复制的方法的调用会在主题中产生错误消息。

我确实查看了 XCode 文档,但我可能只是不知道如何声明它,所以这个方法可以看到它。奇怪的是它看到了 title getter,但没有看到 title2 副本。

4

1 回答 1

3

尝试将行从点符号更改为:

NSString *str2=[annotation title2];

并且错误应该消失。

发生的事情是编译器被告知注解是一个MKAnnotation. 您知道它还有哪些其他方法这一事实无关紧要。编译器不是通灵的——它只知道注解遵循 MKAnnotation 协议,仅此而已。它看到标题 getter 的原因是因为标题是在 MKAnnotation 中定义的。

你也可以通过使用 cast 来解决这个问题:

MapLocation *mapLocation = (MapLocation *)annotation;

现在,你可以说

NSString *str2=mapLocation.title2;

因为您已经告诉编译器 mapLocation 是 MapLocation 对象。

于 2010-05-18T14:48:27.233 回答