Search code examples
iphonemkmapviewmkannotationmkannotationview

Is a MKAnnotation pin connected to the object that holds it? How do I trace back?


I have a NSObject class "MyItem" that holds several instance variables, among them a mapPoint declared in (MyMapPoint *)mapPoint. I use this MKMapPoint to add annotations to a MKMapView. The NSMutablearray "allItems" holds all items.

int all =[allItems count];
int i =0;    
for (i=0; i<all; i++) {

MyItem *p = [allItems objectAtIndex:i];
[mYView addAnnotation:[p mapPoint]];

This works perfect. I get a map full of pins where the items were registered. Also, I get a bubble when I push the pin, which gives title and subtitle. I have also managed to add a callout to the console.

NSLog (@"bubble is pushed");

which also works fine.

Problem: When I push the bubble, I want (to begin with) the console to log the full description of the actuall item the pin represents. Is there any sample code that traces back the to full MyItem? It seems like the pin has no recollection of its origin. All help, samplecode and links to samplecode will be heavilly appriciated.


Solution

  • It sounds like you've got a separate type for your annotations (i.e. whatever is returned by the -mapPoint method). An easier way to deal with this is to implement the MKAnnotation protocol directly in your MyItem class. That way, instead of:

    [mYView addAnnotation:[p mapPoint]];
    

    you can just say:

    [mYView addAnnotation:p];
    

    By adopting MKAnnotation in your data object, you get direct access to the data you need when the user taps an annotation view.

    Another way to go, of course, is to stash a pointer back to your data object in you annotation. That can make more sense if your data objects are large, or if you have very many of them. It doesn't even really have to be an actual object pointer -- you just need to store some piece of information in your annotation that lets you later recover the data object. So, for example, you might include an identifier in your annotation. When the user taps the annotation view, you use the identifier to retrieve the associated data from your data store.

    Short answer: You're responsible for connecting your annotations to your data; the framework doesn't do it for you.