Due to performance reasons, I need to do a binary insert on my annotations list, but after I reached the part where I actually need to insert the annotation, I realized that my mapView is not the same as a NSMutableArray, so I cannot freely add an annotation in the middle of the list.
while (first <= last) {
NSUInteger mid = (first + last)/2;
if ([name compare:[mapView.annotations objectAtIndex:mid]] == NSOrderedDescending) {
first = mid + 1;
} else if ([name compare:[mapView.annotations objectAtIndex:mid]] == NSOrderedAscending) {
last = mid - 1;
} else {
Annotation *destination = [[Annotation alloc] init];
[destination setTitle:name];
[destination setSubtitle:sub];
[destination setCoordinate:coords];
// method doesn't exist, but how do I create/simulate this?
[mapView insertAnnotation:destination atIndex:mid];
[destination release];
return;
}
}
Is it possible to extend mapview and create my own class to do this? If so, how would I go about adding the annotation at the index?
Don't rely on the order of annotations in MKMapView's annotations
property.
The map view will display whichever annotations belong on the screen given the map view's current span and zoom. It may be that internally, the map view doesn't even store the annotations as an array. After all, it needs to be able to find all the annotations that are geographically close to the current region, and an array isn't the structure that's best suited for that.
If you want to keep the annotations sorted a certain way, you should maintain your own array. You can use that array to add the annotations to the map view when you set it up. For updates to the annotation list, however, you should add or remove only those annotations that you've added or removed from your list. That is, it's probably inefficient to remove the entire list of annotations and then add a whole new list when most of the annotations in the new list are the same.