Store data in MKAnnotation?

旧街凉风 提交于 2019-11-26 17:55:39

In the viewForAnnotation method, you can access your ArtPiece properties but to avoid compiler errors and warnings, you'll need to first cast the annotation parameter to your custom class. The annotation parameter in that method is just defined as a id<MKAnnotation> so the compiler won't know about the ArtPiece-specific properties (until you tell it that is an instance of ArtPiece).

You'll need something like this:

ArtPiece *artPiece = (ArtPiece *)annotation;
NSString *artist = artPiece.artist;

Edit:
When an annotation view's callout button is pressed, the map view calls the calloutAccessoryControlTapped delegate method. This method gets passed the MKAnnotationView in the view parameter. The annotation object itself is in the annotation property of the view parameter. You can cast that object to your custom class to access your ArtPiece properties:

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    ArtPiece *artPiece = (ArtPiece *)view.annotation;
    NSString *artist = artPiece.artist;
}

In other words, the callout button handler doesn't need to access the original array. It gets a reference to the actual ArtPiece object itself.

Create a subclass of MKAnnotation and you can add whatever additional data members you need.

kball

There seems to be some confusion here.

MKAnnotation is a protocol, not a class, so you don't subclass it, you implement it. Any object can be an MKAnnotation as long as it implements the MKAnnotation protocol (coordinate, title, subtitle) and that object can have any other property you like if you're creating it. You have done that correctly above.

Oftentimes you will need to cast that <MKAnnotation> to your custom class, as Anna Karenina said, to inform the compiler what type of object it is.

MKAnnotationView on the other hand is a class (and a subclass of UIView), and if you want to create your own you can subclass it. Then when it is created and used by the map it holds a reference to its associated MKAnnotation, so in your custom MKAnnotationView you can:

self.artistLabel.text = [(ArtPiece *)self.annotation artist];
ajay_nasa

Every annotation has unique id. Use NSMutableDictionary and use your annotation unique id as key for any objects you want. later you could access when you call this:

-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!