2011-04-13 18 views
0

此代码来自MapCallouts演示。假设我有数百个不同的注释。苹果公司做到这一点,会导致很多代码重复。更简单的方法来编码多个MKAnnotations?

我想访问触发委托的类的实例的注释属性,而不管哪个类实例触发它。

是否有比编写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; 
    } 

回答

1

你可以有你的所有注解类提供了一些常用的方法,比如-annotationView。你可能从一个公共的超类派生所有的注解类,或者只是创建一个协议。然后,检查注释实际响应选择,或者是你的普通类的子类,并要求它为它的观点:

if ([annotation respondsToSelector:@selector(annotationView)]) { 
    return [annotation annotationView]; 
} 

if ([annotation isKindOfClass:[AbstractAnnotation class]]) { 
    return [annotation annotationView]; 
} 

原因之一做也就是说,用作注释的对象通常是数据模型的一部分,并且他们可能没有任何关于注释视图的知识。能够提供标题,副标题和位置是一回事;提供视图的实际实例通常超出了模型对象应该做的范围。

请记住,注释视图通常不会做太多,除了显示图片并为标注视图提供左侧和右侧配件。是否真的有可能需要数百个不同的注释视图子类?或者,您是否可以对所有注释使用通用的注释视图,并以不同的方式配置它们(例如,通过更改注释视图的图像)?

相关问题