views:

479

answers:

1

I've made a custom MKAnnotation class, MapLocation. I'm having no trouble setting or getting properties, except in this method to create an MKAnnotationView. I need to do it here, since it's supposed to look up a location type from the annotation's index and select one of a family of custom annotation images for the annotationView.

After numerous attempts at setting up custom getters and setters in MapLocation.h and .m, I boiled it down to where I can't even copy the (obligatory) getter, title, rename it to title2, and try to get its return value. This is my code:

-(MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {
static NSString *placemarkIdentifier=@"Map Location Identifier";
NSString *str1=annotation.title;
NSString *str2=annotation.title2;
if([annotation isKindOfClass:[MapLocation class]]) {
    MKAnnotationView *annotationView=(MKAnnotationView *)[theMapView dequeueReusableAnnotationViewWithIdentifier:placemarkIdentifier];
    if (annotationView==nil) {
        annotationView=[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:placemarkIdentifier];
    }
    else
        annotationView.annotation=annotation;


    return annotationView;
}
return nil;

}

On the 4th line, title is returned correctly, but the 5th line's call to the copied method yields the error message in the topic.

I did look in the XCode docs, but I'm probably just not getting how to declare it so this method sees it. Strange that it sees the title getter, but not the title2 copy.

+2  A: 

Hi,

Try changing the line from dot notation to this :

NSString *str2=[annotation title2];

and the error should go away.

What's happening is that the compiler has been told that annotation is an MKAnnotation. The fact that you know what other methods it's got is irrelevent; the compiler is not psychic - all it knows is that annotation follows the MKAnnotation protocol, nothing more. The reason that it sees the title getter is beacuse the title is defined in MKAnnotation.

You can also fix this by using a cast :

MapLocation *mapLocation = (MapLocation *)annotation;

Now, you can say

NSString *str2=mapLocation.title2;

because you've told the compiler that mapLocation is a MapLocation obejct.

deanWombourne
I was actually looking at how to declare a MapLocation protocol when I saw you already answered. So now my annotations have indices which links them to whatever I need, and the correct images for the type of location are shown. Thanks!This didn't work though (I had tried this before): NSString *str2=[annotation title2];It says -title2 is unknown. Doesn't help to declare it in the interface. A bit strange to a newbie like me, "since the compiler shouldn't worry about messages, they are runtime". I do understand now that it would complain about extra properties without a cast, thanks!
Henrik Erlandsson