MKMapView annotations changing/losing order?

后端 未结 2 2047
情书的邮戳
情书的邮戳 2020-11-29 10:57

I have a map view with annotations, and these annotations display a callout. When the callout\'s disclosure detail button is clicked, it segues into a new view.

My

相关标签:
2条回答
  • 2020-11-29 11:07

    When you call addAnnotation or addAnnotations, the map view adds the reference(s) to its internal list of annotations.

    The annotations property of MKMapView simply returns this internal list (whatever type it might be) as an NSArray.

    I don't know of any place in the documentation where it states that the annotations property returns the array in the same order that you added the annotations in. If you have showsUserLocation turned on, the array will include that annotation even though you didn't explicitly add it.

    You do not need to be concerned about nor should you depend on the order of the objects in the annotations property.

    Just a few suggestions regarding the code:

    • Since your array contains objects that implement <MKAnnotation>, instead of looping through it, you can add all the annotations in one shot by calling addAnnotations (plural) and pass it the array
    • In viewForAnnotation, none of the properties you are setting depend on any specific annotation so you can set them all inside the if (av == nil) block. This way you get maximum reuse.
    • Also in viewForAnnotation, after and outside the if, you should set the annotation property of the view to the current annotation. This is in case the view is being reused from another annotation.
    • Finally, in viewForAnnotation, don't assume the annotation will be of type MyClass. If you turn on showsUserLocation, that won't be the case. It's safer to declare the parameter as id<MKAnnotation> and then if necessary check what its class is and then cast it.
    0 讨论(0)
  • 2020-11-29 11:15

    @Anna, you state you should not be concerned for the order of the annotations. That's not true in my case. Some annotationviews might overlap, and I always need a specific one to be on the top of the two overlapping views. So the order DO makes sense for the annotations, as I hope the - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation gets called in the same order as i added the annotations.

    EDIT: and the solution is here :-)

    0 讨论(0)
提交回复
热议问题