Armand Grillet
Armand Grillet

Reputation: 3399

Fatal error when changing all annotations' image in a MKMapView

I'm trying to change all the images of my MKMapView's markers. Here is the code:

for annotation:MKAnnotation in self.annotations as [MKAnnotation] {
    println(annotation.title) // Returns the correct title
    var updatedImage: UIImage! = self.bikeStationsManager.getMarker(annotation.title!, isABikeStation: displayingBikes) // Method to get the new image
    println(updatedImage.size.height) // Returns a value > 0
    self.viewForAnnotation(annotation).image = updatedImage // Fatal error: unexpectedly found nil while unwrapping an Optional value
}

Here is the weird thing: I've 83 markers and when I'm using this code it's crashing every time but not always for the same annotation and neither the annotation or the image returned seem the problem according to println(). So I really don't know what is wrong in my code, does anyone have an idea?

I also tried to update only the first annotation's image for example, it's working.

Upvotes: 1

Views: 268

Answers (1)

zisoft
zisoft

Reputation: 23078

viewForAnnotation returns an optional, according to the documentation:

Return Value

The annotation view or nil if the view has not yet been created. This method may also return nil if the annotation is not in the visible map region and therefore does not have an associated annotation view.

It returns even nil if the annotation is not in the visible area of your map so iterating over a loop of all annotations is not the right approach to change the annotation images.

You have to implement

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {}

of the MKMapViewDelegate protocol and create the annotation view there.

Upvotes: 1

Related Questions