I'm trying to mark a location in a map view.
First I implemented the MKAnnotation
protocol in a separate class like this.
AddressAnnotation.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface AddressAnnotation : NSObject <MKAnnotation>
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
- (id)initWithCoordinates:(CLLocationCoordinate2D)location;
@end
AddressAnnotation.m
#import "AddressAnnotation.h"
@implementation AddressAnnotation
- (id)initWithCoordinates:(CLLocationCoordinate2D)location
{
self = [super init];
if (self)
{
self.coordinate = location;
}
return self;
}
@end
Then in the view controller, I implemented the MKMapViewDelegate
.
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
{
return nil;
}
static NSString *myIdentifier = @"myIndentifier";
MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:myIdentifier];
if (!pinView)
{
pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:myIdentifier];
pinView.pinColor = MKPinAnnotationColorRed;
pinView.animatesDrop = NO;
}
return pinView;
}
And in the viewDidLoad
method, I initialize an instance of the AddressAnnotation
class.
- (void)viewDidLoad
{
[super viewDidLoad];
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(34.421496, -119.70182);
AddressAnnotation *pinAnnotation = [[AddressAnnotation alloc] initWithCoordinates:coordinate];
[self.mapView addAnnotation:pinAnnotation];
}
I keep getting the following error though.
-[AddressAnnotation setCoordinate:]: unrecognized selector sent to instance
I'm not sure what I'm doing wrong here. Can someone please help me out?
Thank you.
The problem is that you defined a readonly coordinate property. Therefore you get an exception when trying to set it. Just remove your coordinate property definition, as this is already provided by the MKAnnotation protocol.