【问题标题】:Add MKAnnotations on a MKMapView from NSArray of coordinates从坐标的 NSArray 在 MKMapView 上添加 MKAnnotations
【发布时间】:2013-01-10 12:16:57
【问题描述】:

我需要在我的 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 (code=1...) 而崩溃。有什么问题,或者在没有冗余代码的情况下添加多个注释的最佳方法是什么?谢谢!

【问题讨论】:

    标签: objective-c nsarray mkmapview


    【解决方案1】:

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

    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];
    }
    

    【讨论】:

    • 绝对优雅,很好的解释。我只需要添加 CoreLocation 框架,你的代码就完美了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多