I’d like to reorder the array of annotations shown on a map in order to create a next/prev button for quickly cycling through all annotations (sorted by date) using a simple iterator.
As far as I see the annotations array used as a store [worldmap annotations] is not mutable and therefore I cannot reorder it. I tried the following to create a temporary copy of the annotations array, sort it by date and re-attach it.
(worldmap is my MKMapView object)
//COPY
NSMutableArray *annotationSort = [[NSMutableArray alloc]initWithArray:[worldmap annotations]];
//SORT
[annotationSort sortedArrayUsingComparator:^NSComparisonResult(EventPin* obj1, EventPin* obj2) {
return [obj1.eventItemObject.eventDateBegin compare: obj2.eventItemObject.eventDateBegin];
}];
//ADDED SORTED ARRAY
[worldmap removeAnnotations:[worldmap annotations]];
[worldmap addAnnotations:annotationSort];
This doesn’t seem to work. Any idea how can I reorder the MKMapKit annotations array?
As the answer in the linked question mentions, there is no guarantee that the map view’s
annotationsproperty will preserve any order.In addition, since the
annotationsproperty includes theuserLocationif you haveshowsUserLocationturned on (but which you don’t yourself explicitly calladdAnnotationfor), the annotation order will not be what you may expect.Don’t rely on the order of the annotations in the map view’s
annotationsarray.Instead, keep your own array of references to the annotations and sort them any way you want (like your
annotationSortarray).But there’s no point in removing them from the map and adding them back.
Keep in mind that the map view’s
annotationsarray may contain theMKUserLocationannotation so when constructing your array, check the type of each annotation before including it or accessing custom properties.However, note that the code to sort the array:
is flawed itself because
sortedArrayUsingComparatorreturns anNSArray.It does not sort the array in-place.
Instead, to sort an
NSMutableArray, call itssortUsingComparatormethod.Using this sorted array, your app can access or select the annotations in the order desired.