2012-03-15 35 views
2

注解显示在地图上,但是当我在一个点击,我的git此异常:NSInvalidArgumentException当试图调用注解

[NSNull length]: unrecognized selector sent to instance 
'NSInvalidArgumentException', reason: '-[NSNull length]: unrecognized selector sent to instance 

我相关的代码是这样的:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { 

    static NSString *identifier = @"MyLocation"; 
    if ([annotation isKindOfClass:[MyLocation class]]) { 

     MKPinAnnotationView *annotationView = (MKPinAnnotationView *) [mapView2 dequeueReusableAnnotationViewWithIdentifier:identifier]; 
     if (annotationView == nil) { 
      annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier]; 
     } else { 
      annotationView.annotation = annotation; 
     } 

     annotationView.enabled = YES; 
     annotationView.canShowCallout = YES; 

     annotationView.pinColor = MKPinAnnotationColorRed; 
     return annotationView; 
    } 

    return nil;  
} 

而且配置注释:

NSNumber * latitude = [[row objectAtIndex:21]objectAtIndex:1]; 
     NSNumber * longitude = [[row objectAtIndex:21]objectAtIndex:2]; 
     NSString * crimeDescription = [row objectAtIndex:17]; 
     NSString * address = [row objectAtIndex:13]; 

     CLLocationCoordinate2D coordinate; 
     coordinate.latitude = latitude.doubleValue; 
     coordinate.longitude = longitude.doubleValue;    
     MyLocation *annotation = [[MyLocation alloc] initWithName:crimeDescription address:address coordinate:coordinate] ; 
     [mapView2 addAnnotation:annotation]; 

而且在MyLocation类中包含注释:

- (id)initWithName:(NSString*)name address:(NSString*)address coordinate:(CLLocationCoordinate2D)coordinate { 
    if ((self = [super init])) { 
     _name = [name copy]; 
     _address = [address copy]; 
     _coordinate = coordinate; 
    } 
    return self; 
} 
+0

也许这 http://stackoverflow.com/questions/2377833/mkmapkit-exception-when-using-canshowcallout-on-annotation-view – 2012-03-16 00:57:41

回答

6

当您点击在注释视图,它会尝试获取的注释的title所以它知道有多宽,使标注的length

您收到的例外表示该注释的title设置为NSNull对象而不是NSString

一个NSNull对象没有length方法,所以你得到那个“无法识别的选择器”异常。


您还没有表现出title如何在MyLocation类中实现的,但我认为它返回_name要为其设置到crimeDescription创建注释时(这是从row阵列)。

不知何故,row阵列中的值有一个NSNull而不是NSString

如果您不需要NSNull值,你可以更改设置row数组值,因此不会把NSNull是代码(它可以把NSString就像@"Unknown"代替)。

另一种选择是,你可以修改为title getter方法在MyLocation类,并将它返回一个“未知” NSString如果_nameNSNull

例如:

-(NSString *)title 
{ 
    if ([_name isKindOfClass:[NSNull class]]) 
     return @"Unknown"; 
    else 
     return _name; 
} 
+0

感谢名单上百万:) – Luca 2012-03-16 10:38:08