ios - Mapkit 中 NSMutableArray 的多个注释

标签 ios ipad mkannotation cllocation mapkit

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

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 和编程新手,所以请保持温柔。

最佳答案

您只有一个 myAnnotation5 对象。当您设置其坐标标题等时,您正在为该实例进行设置,而您恰好已多次将其添加到注释中。因此,annotations 中的每个条目都将具有您设置的最后一组属性 - 因为 annotations 中的每个条目实际上都是相同对象。

为了解决这个问题,您需要在循环的每次迭代中重新创建 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/

相关文章:

ios - 在 <= iOS 8 中是可以的。但是 iOS 9,我收到错误

ios - UIDocumentInteractionController 删除操作菜单

iphone - 如何以编程方式安装 iOS 应用程序?

iphone - 在设备上进行测试时向SIGABRT发出信号,它可在模拟器上运行。简易代码

ios - MKMapView:自定义 View 代替 Annotation Pin

ios - 如何在不隐藏分隔符的情况下更改单元格文本颜色?

ios - 具有 IP 地址的通用链接

iphone - 如何从 MKMapview 中删除国家/州名称

ios - MKPointAnnotation 表达式不可分配

ios - Objective-C ,[NSString initWithFormat] 究竟是做什么的?