I have a map setup to show an annotation with this code:
var newAnnotation = MKPointAnnotation()
if newPostJustPosted {
var newPostCoordinate = CLLocationCoordinate2DMake(userPosts.last!.postLatitude, userPosts.last!.postLongitude)
newAnnotation.coordinate = newPostCoordinate
newAnnotation.title = userPosts.last!.postTitle
mainMapView.addAnnotation(newAnnotation)
newPostJustPosted = false
println("New post was just posted")
}
This runs no problem, and the annotation shows up. After this, I tried to place an array of annotations via this code:
if userPosts.count > 0 {
for eachPost in 0...userPosts.count - 1 {
var currentPost = userPosts[eachPost]
newAnnotation.coordinate = CLLocationCoordinate2DMake(currentPost.postLatitude, currentPost.postLongitude)
println("Latitude is: " + "\(currentPost.postLatitude)")
newAnnotation.title = currentPost.postTitle
mainMapView.addAnnotation(newAnnotation)
println("This Ran")
}
}
According to the console, the Latitude and Longitude are correct, and the code is running the correct number of times, but no annotations show up on the map. I've now spent hours looking over this code and if it's something simple I'm going to feel so dumb. Either way, any help would be appreciated! Thanks!
In the documentation for
addAnnotation
, it says:That means when you call
addAnnotation
, the map view keeps a reference to that exact object not only for itself, but for you when it calls delegate methods related to an annotation such asviewForAnnotation
.The map view will need to let you know exactly which annotation it's talking about.
The annotation objects can be completely custom classes (as long as they conform to the
MKAnnotation
protocol) and instead of going through the possibly tedious, time consuming, and maybe impossible task of making copies of the objects passed toaddAnnotation
, it simply keeps references to those exact objects.In the code in the question, only the first call to
addAnnotation
in the loop adds a new annotation to the map.The following calls end up only modifying that existing annotation's
coordinate
andtitle
.Now, it might be nice if
addAnnotation
at least gave a run-time warning in the console such as "Annotation with this pointer reference already exists -- not adding it again" but it doesn't.Instead, it just ignores the request to add it again.
What must be happening is that the one annotation that is added is at the last coordinates in the array.
The fix is to create a new instance of an annotation object for each annotation you want to add.