编码多个MKAnnotations的更简单方法?

| 该代码来自MapCallouts演示。说我有数百个不同的注释。苹果这样做的方式将导致很多代码重复。 我想访问触发委托的类实例的注释属性,而不管哪个类实例触发了它。 有没有比编写if语句来处理每个注释并具有一个通用方法更简单的方法?
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation
    {
        // if it\'s the user location, just return nil.
        if ([annotation isKindOfClass:[MKUserLocation class]])
            return nil;

        // handle our two custom annotations
        //
        if ([annotation isKindOfClass:[BridgeAnnotation class]]) // for Golden Gate Bridge
        {
            //do something   
        }
        else if ([annotation isKindOfClass:[SFAnnotation class]])   // for City of San Francisco
        {
            //do something
        }

        return nil;
    }
    
已邀请:
您可以让所有注释类都提供一些通用方法,例如
-annotationView
。您可以从一个公共的超类派生所有注释类,或者仅创建一个协议。然后,检查注释是否确实对选择器做出了响应,或者它是您的通用类的子类,并要求其提供视图:
if ([annotation respondsToSelector:@selector(annotationView)]) {
    return [annotation annotationView];
}
要么
if ([annotation isKindOfClass:[AbstractAnnotation class]]) {
    return [annotation annotationView];
}
不这样做的一个原因是,用作批注的对象通常是数据模型的一部分,并且它们可能没有任何业务了解批注视图。能够提供标题,字幕和位置是一回事;提供视图的实际实例通常超出模型对象应做的范围。 请记住,注解视图除了显示图片并为标注视图提供左右附件外,通常不会做太多其他事情。您是否真的需要数百个不同的批注视图子类?还是可以对所有注释使用通用的注释视图,然后仅对其进行不同的配置(例如通过更改注释视图的图像)?     

要回复问题请先登录注册