此函数接受纬度/经度对数组。它将所有这些转换为MKAnnotation
s,然后对于当前在地图上显示的每个注释,它会检查它是否存在于新的注释集中。如果它存在,则按原样保留注释,否则将其删除。
然后,对于每个新注释,它检查它当前是否在地图上;如果是,则保留它,否则将其删除。
这显然是非常密集的,我想知道是否有更快的方法吗?
- (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];
});
});
}
答案 0 :(得分:3)
你可以使用removeObjectsInArray:(NSArray *)。
例如:
NSMutableArray *annotationsToRemove = [[NSMutableArray alloc] initWithArray:[mapView annotations]];
[annotationsToRemove removeObjectsInArray:annotationsArray];
NSMutableArray *annotationsToAdd = [[NSMutableArray alloc] initWithArray:annotationsArray];
[annotationsToAdd removeObjectsInArray:[mapView annotations]];
它假设您的注释实现了hash和isEqual:但应该更有效。