I am working on display a map with annotation on it. What I have so far is
Annotation.h
#import <MapKit/MKAnnotation.h>
#import <Foundation/Foundation.h>
@interface Annotation : NSObject <MKAnnotation>
@end
MapViewController.m
Annotation *pin = [[Annotation alloc] init];
[pin title] = storeName;
[pin subtitle] = storeAddress;
[pin coordinate] = region.center;
[mapView addAnnotation:pin];
However, I got an error like below:
expression is not assignable for title, subtitle and coordinate
Does anyone have any idea about this issue?
First, these lines try to assign a value to a method call which is what the error is saying you can't do:
[pin title] = storeName;
[pin subtitle] = storeAddress;
[pin coordinate] = region.center;
They should be like this:
pin.title = storeName;
pin.subtitle = storeAddress;
pin.coordinate = region.center;
However, the MKAnnotation
protocol defines the properties as readonly
. To be able to set them, declare them in your Annotation
class as:
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
and add the @synthesize
lines for them in Annotation.m
.
However, if all you need are the title
, subtitle
, and coordinate
properties, you don't need to create your own class to implement MKAnnotation
. Instead, just use the built-in MKPointAnnotation
class which already implements those properties as settable:
MKPointAnnotation *pin = [[MKPointAnnotation alloc] init];
Another option, as @macbirdie points out, is just to make your existing Store
class (if you have one) implement the MKAnnotation
protocol.