【问题标题】:How to reorder MKMapView annotations array如何重新排序 MKMapView 注释数组
【发布时间】:2012-10-12 14:37:43
【问题描述】:

我想重新排列地图上显示的注释数组,以便创建一个下一个/上一个按钮,以便使用简单的迭代器快速循环浏览所有注释(按日期排序)。

据我所知,用作存储的 annotations 数组 [worldmap annotations] 是不可变的,因此我无法对其重新排序。我尝试了以下方法来创建注释数组的临时副本,按日期对其进行排序并重新附加它。

世界地图是我的 MKMapView 对象)

//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];

这似乎不起作用。知道如何重新排序 MKMapKit 注释数组吗?

【问题讨论】:

标签: objective-c annotations mkmapview mapkit


【解决方案1】:

正如linked question 中的答案所述,不能保证地图视图的annotations 属性将保留任何顺序。

此外,由于annotations 属性包括 userLocation 如果你打开了showsUserLocation(但你自己没有明确地调用addAnnotation),注释订单不会是您所期望的。

不要依赖地图视图的annotations 数组中注释的顺序

相反,请保留您自己的注释引用数组,并按您想要的方式对它们进行排序(例如您的 annotationSort 数组)。
但是将它们从地图中删除并重新添加是没有意义的。

请记住,地图视图的 annotations 数组可能包含 MKUserLocation 注释,因此在构建数组时,请在包含每个注释或访问自定义属性之前检查每个注释的类型。


但是,请注意对数组进行排序的代码:

[annotationSort sortedArrayUsingComparator:...

本身存在缺陷,因为 sortedArrayUsingComparator 返回 NSArray
它不会就地对数组进行排序。

相反,要对NSMutableArray 进行排序,请调用其sortUsingComparator 方法。


使用此排序数组,您的应用可以按所需顺序访问或选择注释。

【讨论】:

    猜你喜欢
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多