【问题标题】:Multiple Annotations from NSMutableArray in mapkitmapkit 中 NSMutableArray 的多个注释
【发布时间】:2012-05-14 16:52:25
【问题描述】:

我有一个从 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];
}

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

非常感谢任何帮助。

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

【问题讨论】:

  • 什么是myAnnotation1?您是否希望您的 annotations 数组包含您要添加到地图中的所有注释对象?
  • 抱歉在代码中输入了错误的行,但现在已被编辑。我的数组中有 6 个对象,但可能介于 0 到 10 之间。我正在尝试为每个对象获取注释,而不必对每个对象进行硬编码
  • P.S.- 'myAnnotation5.title=[NSString stringWithFormat:@"%@"entity.EntityNo]' 行甚至不应该在没有逗号的情况下编译(在我的答案中添加)。请确保在提问时复制并粘贴您的准确代码。

标签: ios ipad mkannotation cllocation mapkit


【解决方案1】:

您只有一个myAnnotation5 对象。当您设置它的coordinatetitle 等时,您就是在为该实例设置它,而您恰好多次添加到annotations。因此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 的引用即可。

【讨论】:

  • 感谢您的帮助,在第一次尝试时完美运行,是的,我正在使用 ARC。
  • @charliejohnston 很高兴能提供帮助。
  • @ConradShultz 我有类似的问题,是否可以帮助我编写代码?我想使用手势在我的 mapView 上放置图钉注释。我有代码,但不确定在哪里使用它...
  • @cameron 请自行发布您的问题。
【解决方案2】:

移动这一行:

MyAnnotation* myAnnotation5=[[MyAnnotation alloc] init];

在设置 myAnnotation5 的属性之前进入 for 循环。

现在的方式是,您只创建一个MyAnnotation 对象并反复修改其属性。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 2021-05-03
相关资源
最近更新 更多