How to reorder MKMapView annotations array

2020-02-07 07:08发布

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?

1条回答
放荡不羁爱自由
2楼-- · 2020-02-07 07:39

As the answer in the linked question mentions, there is no guarantee that the map view's annotations property will preserve any order.

In addition, since the annotations property includes the userLocation if you have showsUserLocation turned on (but which you don't yourself explicitly call addAnnotation for), the annotation order will not be what you may expect.

Don't rely on the order of the annotations in the map view's annotations array.

Instead, keep your own array of references to the annotations and sort them any way you want (like your annotationSort array).
But there's no point in removing them from the map and adding them back.

Keep in mind that the map view's annotations array may contain the MKUserLocation annotation 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:

[annotationSort sortedArrayUsingComparator:...

is flawed itself because sortedArrayUsingComparator returns an NSArray.
It does not sort the array in-place.

Instead, to sort an NSMutableArray, call its sortUsingComparator method.


Using this sorted array, your app can access or select the annotations in the order desired.

查看更多
登录 后发表回答