OGeek|极客世界-中国程序员成长平台

标题: ios - mapkit 中 NSMutableArray 的多个注释 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 20:54
标题: ios - mapkit 中 NSMutableArray 的多个注释

我有一个从 ios 中的 sqlite db 填充的 mutablearray。我已经获得了正确加载和查看的注释。我的问题是如何编写一个循环来添加数组大小的注释。我已经尝试了以下代码并获取并显示数组中的最后一个条目

NSMutableArray *annotations=[[NSMutableArray alloc] init];
CLLocationCoordinate2D theCoordinate5;
MyAnnotation* myAnnotation5=[[MyAnnotation alloc] init];
for (int i = 0; i < _getDBInfo.count; i++) {

    dbInfo *entity = [_getDBInfo objectAtIndex:i];

    NSNumber *numlat=[[NSNumber alloc] initWithDouble:[entity.Latitude doubleValue]];
    NSNumber *numlon=[[NSNumber alloc] initWithDouble:[entity.Longitude doubleValue]];
    NSLog(@"%d",[_getDBInfo count]);
    la=[numlat doubleValue];
    lo=[numlon doubleValue];
    theCoordinate5.latitude=la;
    theCoordinate5.longitude=lo;

    myAnnotation5.coordinate=theCoordinate5;
    myAnnotation5.title=[NSString stringWithFormat"%@"entity.EntityNo];
    myAnnotation5.subtitle=[NSString stringWithFormat"%@",entity.EntityName]; 
    [mapView addAnnotation:myAnnotation5];
    [annotations addObject:myAnnotation5];
}

我想我的问题是如何根据数组中的计数创建并添加到 View 注释对象?

非常感谢任何帮助。

我是 iOS 和编程新手,所以请保持温和。



Best Answer-推荐答案


您只有一个 myAnnotation5 对象。当你设置它的 coordinatetitle 等时,你是在为那个实例设置它,你碰巧已经多次添加到 annotations .因此,annotations 中的每个条目都将具有您设置的最后一组属性 - 因为 annotations 中的每个条目实际上都是 same 对象。

要解决这个问题,您需要在循环的每次迭代中重新创建 myAnnotation5 对象,即

for (int i = 0; i < _getDBInfo.count; i++) {
    MyAnnotation* myAnnotation5=[[MyAnnotation alloc] init];
    ...
    myAnnotation5.coordinate=theCoordinate5;
    myAnnotation5.title=[NSString stringWithFormat"%@", entity.EntityNo];
    myAnnotation5.subtitle=[NSString stringWithFormat"%@", entity.EntityName];
    ...
    [mapView addAnnotation:myAnnotation5];
}

两旁:

  1. 我希望您使用 ARC 构建,否则您会左右泄漏内存。
  2. 由于 MKMapView 具有 -annotations 属性,您可能没有理由保留自己的 annotations 数组 - 只需保留引用即可到 mapView

关于ios - mapkit 中 NSMutableArray 的多个注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10587724/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4