fuzzygoat
fuzzygoat

Reputation: 26223

Updating MKMapView Annotations from Updated array?

I am working with an NSMutableArray of objects that conform to the MKAnnotation protocol. My question is over time new objects are added to the array, can anyone tell me what is the preferred method for updating the annotations on the mapView. Should I be looking at removing all the pins before adding back the updated array, or would I be better to mark/tag existing pins in the MKAnnotation object and only add back the new (un-tagged) pins?

Upvotes: 1

Views: 3802

Answers (1)

user467105
user467105

Reputation:

Removing all the pins and adding back the whole array including the new annotations will result in flicker and unnecessarily redrawing pins that haven't changed.

Unless the flicker is desired or a full refresh is necessary for some reason, it's better to just tell the map view to add the new pins.

After your main annotation array is updated with the new pins, construct a temporary array called say newAnnots containing references to the new annotations in the main array and pass newAnnots to the map view's addAnnotations: method. The temporary array can be discarded afterwards.

However, instead of using tagging to identify "new" annotations, you could just check if the annotation object in your main array already exists in the map view's annotations array. For example:

if (![mapView.annotations containsObject:annot_from_your_main_array]) {
    [newAnnots addObject:annot_from_your_main_array];
}

Comparing with the map view's annotations array will only work if the annotation objects in your main array are the actual annotations you give to the map view in addAnnotation: or addAnnotations:. Also, when your main array is "updated", it should only add the new annotations instead of rebuilding the whole array from scratch. If it does, the annotation references won't match with the ones in the map view's array.

The same applies if you are removing annotations on an update. The removed annotations could be added to a temporary "remove" list (by checking if annotations in the map view's array exist in your array) and passed to removeAnnotations:.

Note that if you update an existing annotation's coordinates in your main array, the map view will automatically update the pin's location as long as the annotation object in your array implements the setCoordinate: method.

Upvotes: 6

Related Questions