【发布时间】:2011-08-19 11:52:09
【问题描述】:
这个函数接受一个纬度/经度对的数组。它将所有这些转换为MKAnnotations,然后对于地图上当前存在的每个注释,它检查它是否存在于新的注释集中。如果存在,则保留注释,否则将其删除。
然后对于每个新注释,它会检查它当前是否在地图上;如果是,则保留它,否则将其删除。
这显然非常密集,我想知道是否有更快的方法?
- (void)setAnnotationWithArray:(NSArray *)array {
static BOOL processing = NO;
if (processing) {
return;
}
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
processing = YES;
NSMutableArray *annotationsArray = [NSMutableArray arrayWithCapacity:[array count]];
NSMutableArray *annotationsToRemove = [NSMutableArray array];
for (NSDictionary *dict in array) {
NSString *latStr = [dict objectForKey:@"Latitude"];
NSString *lonStr = [dict objectForKey:@"Longitude"];
NSString *title = [dict objectForKey:@"Location"];
double lat = [latStr doubleValue];
double lon = [lonStr doubleValue];
CLLocationCoordinate2D location;
location.latitude = lat;
location.longitude = lon;
MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] initWithTitle:title andCoordinate:location];
[annotationsArray addObject:newAnnotation];
[newAnnotation release];
}
for (id<MKAnnotation> oldAnnotation in [mv annotations]) {
CLLocationCoordinate2D oldCoordinate = [oldAnnotation coordinate];
BOOL exists = NO;
for (MapViewAnnotation *newAnnontation in annotationsArray) {
CLLocationCoordinate2D newCoordinate = [newAnnontation coordinate];
if ((newCoordinate.latitude == oldCoordinate.latitude)
&& (newCoordinate.longitude == oldCoordinate.longitude)) {
exists = YES;
break;
}
}
if (!exists) {
[annotationsToRemove addObject:oldAnnotation];
}
}
[annotationsArray removeObjectsInArray:[mv annotations]];
dispatch_async( dispatch_get_main_queue(), ^{
processing = NO;
[mv removeAnnotations:annotationsToRemove];
[mv addAnnotations:annotationsArray];
});
});
}
【问题讨论】:
-
你确定
[annotationsArray removeObjectsInArray:[mv annotations]];这行真的有效吗?您正在创建 new 注释对象并将它们放入 annotationsArray。这些新对象不会“等于”[mv annotations]中的对象(即使属性值匹配),除非您按照 Zoleas 所说的那样实现了isEqual。如果该行不执行任何操作,则每次调用此方法时,您最终都会在地图上添加重复的注释副本(可能会导致性能下降)。
标签: objective-c ios cocoa-touch mkmapview mkannotation