How to reorder MKMapView annotations array

心不动则不痛 提交于 2019-11-28 14:26:20

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!