Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

objective c - How to reorder MKMapView annotations array

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...