To remove some annotations from an MKMapView
, but not all of them, based on some condition, there seems to be 3 ways. I'd like to know which is the best one, and if there are any pitfalls with any of them. Thank you.
First way: removing annotations from annotations directly
for (id<MKAnnotation> annotation in self.mapView.annotations) {
if ([annotation isKindOfClass:[PinAnnotation class]]) {
[self.mapView removeAnnotation:annotation];
}
}
As the docs say, the mapView annotations
property is readonly
. So I assume it's a copy that I can safely manipulate.
Documentation: @property(nonatomic, readonly) NSArray <id<MKAnnotation>> *annotations
Second way: adding the unwanted annotation to an array first
NSInteger toRemoveCount = myMap.annotations.count;
NSMutableArray *toRemove = [NSMutableArray arrayWithCapacity:toRemoveCount];
for (id annotation in myMap.annotations){
if (annotation != myMap.userLocation){
[toRemove addObject:annotation];
}
}
[myMap removeAnnotations:toRemove];
This code is copied from the example found here
It seems safer, but there's the overhead of creating the mutable array. If it's not necessary, I'd rather avoid it.
Third way : filtering the array
[_mapView.annotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"!(self isKindOfClass: %@)", [MKUserLocation class]]];
(answer found here: https://stackoverflow.com/a/2915063/873436).
I didn't try out this one, but it seems rather elegant and powerful.
What's the best way?
Is it dangerous to remove annotations while itering through them?
Thank you for your knowledge and insights!