从坐标的NSArray在MKMapView上添加MKAnnotations

时间:2013-01-10 12:16:57

标签: objective-c nsarray mkmapview

我需要在我的MKMapView上添加几个注释(一个国家/地区的每个城市的示例一个),我不想初始化所有城市的纬度和经度的每个CLLocation2D。我认为有可能使用数组,所以这是我的代码:

NSArray *latit = [[NSArray alloc] initWithObjects:@"20", nil]; // <--- I cannot add more than ONE object
NSArray *longit = [[NSArray alloc] initWithObjects:@"20", nil]; // <--- I cannot add more than ONE object

// I want to avoid code like location1.latitude, location2.latitude,... locationN.latitude...

CLLocationCoordinate2D location;
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];

for (int i=0; i<[latit count]; i++) {
    double lat = [[latit objectAtIndex:i] doubleValue];
    double lon = [[longit objectAtIndex:i] doubleValue];
    location.latitude = lat;
    location.longitude = lon;
    annotation.coordinate = location;
    [map addAnnotation: annotation];
}

好吧,如果我在NSArrays latit和longit中留下一个对象,它就可以了,我在地图上有一个注释;但是,如果我向数组应用程序版本添加多个对象,但崩溃与EXC_BAD_ACCESS(代码= 1 ...)。有什么问题,或者在没有冗余代码的情况下添加多个注释的最佳方法是什么?谢谢!

1 个答案:

答案 0 :(得分:3)

您使用的是相同的注释对象,即:

MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];

在for循环中移位它,或在添加到地图之前复制它。

解释:这是MKAnnotation协议中的注释属性:

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

如您所见,它不是复制对象,因此如果您始终添加相同的注释,则会有重复的注释。如果在时间1添加带坐标(20,20)的注释,则在时间2将注释坐标更改为(40,40)并将其添加到地图中,但它是同一个对象。

此外,我不建议将NSNumber个对象放入其中。而是创建一个唯一的数组并填充CLLocation个对象,因为它们用于存储坐标。 CLLocation类具有以下属性:

@property(readonly, NS_NONATOMIC_IPHONEONLY) CLLocationCoordinate2D;

它也是一个不可变对象,因此您需要在创建对象时初始化此属性。使用initWithLatitude:longitude:方法:

- (id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude;

所以你可以写一个更好的代码版本:

#define MakeLocation(lat,lon) [[CLLocation alloc]initWithLatitude: lat longitude: lon];

NSArray* locations= @[ MakeLocation(20,20) , MakeLocation(40,40) , MakeLocation(60,60) ];

for (int i=0; i<[locations count]; i++) {
    MKPointAnnotation* annotation= [MKPointAnnotation new];
    annotation.coordinate= [locations[i] coordinate];
    [map addAnnotation: annotation];
}