我有一个可变数组,它是从 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];
}
两点补充:
- 我希望您使用 ARC 进行构建,否则您会左右泄漏内存。
- 由于
MKMapView
有一个-annotations
属性,因此您可能没有理由保留自己的annotations
数组 - 只需保留一个引用到mapView
。
关于ios - Mapkit 中 NSMutableArray 的多个注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10587724/