枚举 - 发送到实例的无法识别的选择器

时间:2011-03-03 14:04:35

标签: objective-c ios mkmapview

我尝试访问我的枚举,但它不起作用!!!

我在Annotation.h中创建了一个typedef枚举,我尝试在另一个类中访问枚举的一个元素......

typedef enum 
{
    AnnotationTypeMale = 0,
    AnnotationTypeFemale = 1
} AnnotationType;

@interface Annotation : NSObject <MKAnnotation> 
{

    CLLocationCoordinate2D coordinate;
    NSString *title;
    NSString *subtitle;
    AnnotationType annotation_type;
}



@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic,retain) NSString *title;
@property (nonatomic,retain) NSString *subtitle;
@property (nonatomic,getter=getAnnotationType,setter=setAnnotationType) AnnotationType        annotation_type;

@end

这是我的Annotation.h和我的Annotation.m我综合了所有,我也包括Annotation.h ... 在我的其他课程中,我现在尝试访问AnnotationType ...

- (AnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation
 {
AnnotationView *annotationView = nil;


// determine the type of annotation, and produce the correct type of annotation view for it.
Annotation* myAnnotation = (Annotation *)annotation;



if([myAnnotation getAnnotationType] == AnnotationTypeMale)
{

if语句不起作用..发生此错误:由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:' - [MKUserLocation getAnnotationType]:无法识别的选择器发送到实例0x5c43850'

任何解决方案?????? THX

1 个答案:

答案 0 :(得分:6)

错误说[MKUserLocation getAnnotationType]: unrecognized selector...。这意味着viewForAnnotation方法试图在类型为MKUserLocation的注释上调用getAnnotationType。

在地图视图中,showsUserLocation必须设置为YES,这意味着除了MKUserLocation类型的注释之外,地图还为用户的位置添加了自己的蓝点注释(类型为Annotation)你正在补充。

在viewForAnnotation中,您需要先检查注释的类型,然后再像Annotation那样对其进行处理。由于您没有检查,代码会尝试在每种类型的注释上调用getAnnotationType,而不管类型如何,但MKUserLocation没有这样的方法,因此您将获得异常。

您可以检查注释是否为MKUserLocation类型,并立即返回nil:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;

    //your existing code...
}

或检查注释是否为Annotation类型并执行该特定代码:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    MKAnnotationView *annotationView = nil;

    if ([annotation isKindOfClass:[Annotation class]])
    {
        // determine the type of annotation, and produce the correct type of annotation view for it.
        Annotation* myAnnotation = (Annotation *)annotation;

        if([myAnnotation getAnnotationType] == AnnotationTypeMale)
        {
            //do something...
        }
        else
            //do something else…
    }

    return annotationView;
}