Dave
Dave

Reputation: 3

Swift MapKit Annotations

I am attemping to add annotations to my app I am having trouble appending to AnyObject. The two entries (Annotation 1 Detail and 2) seem to append to the object except the second annotation overrides the first entry and I end up with 2 objects with the same detail from annotation 2.

    var locations = [AnyObject]()
    var myAnnotation = MKPointAnnotation()

    // Annotation 1 Detail
    myAnnotation.coordinate = CLLocationCoordinate2DMake(-38.219836, 146.246249)
    myAnnotation.title = "Annotation Pin 1"
    myAnnotation.subtitle = "Pin 1"
    locations.append(myAnnotation)

    // Annotation 2 Detail
    myAnnotation.coordinate = CLLocationCoordinate2DMake(-37.219836, 146.246249)
    myAnnotation.title = "Annotation Pin 2"
    myAnnotation.subtitle = "Pin 2"
    locations.append(myAnnotation)

Upvotes: 0

Views: 406

Answers (1)

matt
matt

Reputation: 535138

var myAnnotation = MKPointAnnotation()
// ...
locations.append(myAnnotation)
// ...
locations.append(myAnnotation)

In the first line, you make one MKPointAnnotation object. An MKPointAnnotation is a class instance - a reference type. myAnnotation is therefore the same object each time. You are just appending two references to it into your array. They are not magically copied! They are two references to one and the same thing.

So your changes to myAnnotation after appending the reference for the first time change what the first reference is pointing to, because it is still pointing to the same object. Simpler example:

class Dog {
    var name : String = ""
}

var arr : [Dog] = []

var d = Dog()
d.name = "Rover"
arr.append(d)
d.name = "Fido"
arr.append(d) // now arr is [{name "Fido"}, {name "Fido"}]

Easy solution: make two MKPointAnnotation objects! Ooooh, what a concept!!! Configure them separately, add them to the array separately. Problem solved.

class Dog {
    var name : String = ""
}

var arr : [Dog] = []

var d = Dog()
d.name = "Rover"
arr.append(d)
d = Dog() // oooh! what a concept! _another_ Dog!!!!
d.name = "Fido"
arr.append(d) // now arr is [{name "Rover"}, {name "Fido"}]

Upvotes: 1

Related Questions