Reading off annotations of MKMapViews in NSArray

2019-09-14 17:24发布

问题:

I am trying to find the coordinates of an annotation in many MKMapViews in this way:

NSMutableArray *latitudes = [NSMutableArray array];

for (MKMapView *map in MapViewArray)
{
  NSString *latitude = [NSString stringWithFormat:@"%.2f", [map.annotations lastObject].coordinate.latitude];                       
  [latitudes addObject: latitude];
}

NSMutableArray *longitudes = [NSMutableArray array];

for (MKMapView *map in MapViewArray)
{
     NSString *longitude = [NSString stringWithFormat:@"%.2f", [map.annotations lastObject].coordinate.latitude];


    [longitudes addObject: longitude];
}

This code though gives me this error:

property 'coordinate' not found on object of type id

How can I solve it??

The map views in the array are of this type:

@property (nonatomic, retain) IBOutlet MKMapView *mapView2;

回答1:

You must specify the MKAnnotation protocol to make it compile:

NSMutableArray *latitudes = [NSMutableArray array];
NSMutableArray *longitudes = [NSMutableArray array];

for (MKMapView *map in MapViewArray)
{
    id<MKAnnotation> annotation = [map.annotations lastObject];
    NSString *latitude = [NSString stringWithFormat:@"%.2f", annotation.coordinate.latitude];                       
    NSString *longitude = [NSString stringWithFormat:@"%.2f", annotation.coordinate.latitude];        
    [longitudes addObject: longitude];
    [latitudes addObject: latitude];
}

Also I optimized your code to use only one loop.