MKMapkit的错误不允许我在地图上显示标记

时间:2013-09-09 04:14:55

标签: ios objective-c json mapkit

我遇到了JSON响应问题。出于某种原因,每次运行程序时我都会遇到线程错误,也许这与错误有关......?我正在尝试接受JSON响应,并根据JSON请求使用一组标记填充地图。

NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:queue
     completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
         if([data length] > 0 &&
            error == nil){
             NSData *jsonData = [NSData dataWithContentsOfURL:url];

             if (jsonData != nil){
                 NSError *error = nil;

                 self.results = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];


                 if(error == nil)

                     self.locations = _results;
                 for (NSDictionary *locations1 in self.locations){
                     CLLocationCoordinate2D annotationCoordinate =
                     CLLocationCoordinate2DMake([locations1[@"latitude"] doubleValue], [locations1[@"longitude"] doubleValue]);
                     Annotation *annotation2 = [[Annotation alloc] init];
                     annotation2.coordinate = annotationCoordinate;
                     annotation2.title = locations1[@"name"];
                     annotation2.subtitle = nil;
                     [self.mapView addAnnotation:annotation2];
    **ERROR: sending 'Annotation *__strong' to parameter of incompatible type 'id<MKAnnotation>'
                 }

我不确定我的代表会出现什么问题?有什么想法吗?

1 个答案:

答案 0 :(得分:0)

问题无疑是Annotation未定义为符合MKAnnotation协议。它应该被定义为:

@interface Annotation : NSObject <MKAnnotation>
// ...
@end

或者您可以将Annotation替换为MKPointAnnotation,代码也应该有效。 (你真的需要自己的注释类吗?)

最后,并且无关,您在完成块中执行了dataWithContentsOfURL,但这是不必要的,因为sendAsynchronousRequest已经为您检索了数据,并且已经传递给您的completionHandler

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
     if ([data length] > 0 && error == nil) {
         NSError *error = nil;

         self.results = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

         if (error == nil)
             self.locations = _results;

         for (NSDictionary *location in self.locations) {
             CLLocationCoordinate2D annotationCoordinate = CLLocationCoordinate2DMake([location[@"latitude"] doubleValue], [location[@"longitude"] doubleValue]);
             Annotation *annotation = [[Annotation alloc] init];
             annotation.coordinate = annotationCoordinate;
             annotation.title = location[@"name"];
             annotation.subtitle = nil;
             [self.mapView addAnnotation:annotation];
         }
     }
 }];