Rafael
Rafael

Reputation: 388

How to store an attribute with a MKAnnotation

I'm creating a map with custom pins, using this line

self.mapView.addAnnotation(customMapAnnotationView.annotation!)

But I need later to iterate through all pins and match them with a key that will identify if they are to be removed.

for annotation:ChatRoomMapAnnotationView in self.chatMapView.annotations {
 ...
}

How can I store this key along with the annotation so it's available when I iterate?

Thank you

Upvotes: 0

Views: 92

Answers (2)

Vlad Pulichev
Vlad Pulichev

Reputation: 3272

You need to has custom class for annotation:

class CustomPin: MKPointAnnotation {
   var yourVar1: yourType1
   var yourVar2: yourType2
   // ...
   var yourVar3: yourType3
}

Then your can use it like this:

if annotation is CustomPin {
     // do something
}

Hope it helps

Upvotes: 0

RichardMoult
RichardMoult

Reputation: 100

If I understand correctly, if you wish to store extra information in an annotation you'll need to create a class that conforms to MKAnnotation, like so

class ChatRoomMapAnnotationView: NSObject, MKAnnotation {

let myKeyIdentifier: String
let coordinate: CLLocationCoordinate2D
let title: String?
let subtitle: String?

init(myKeyIdentifier: String, coordinate: CLLocationCoordinate2D, title: String?=nil, subtitle: String?=nil ) {
    self.myKeyIdentifier = myKeyIdentifier
    self.coordinate = coordinate
    self.title = title
    self.subtitle = subtitle
}
}

self.mapView.addAnnotation(CustomMapAnnotationView(.....))

for annotation in self.chatMapView.annotations {
    if let chatAnnotation = annotation as? ChatRoomMapAnnotationView {
       if chatAnnotation.myKeyIdentifier == "specialKey" {
          // do something special
       }
    }
}

Upvotes: 1

Related Questions