我对 iOS6 mapkit 有一些疑问。我尝试创建一个简单的应用程序来显示我的当前位置并向我的 MapView 控件添加自定义注释。这是我的代码:
@interface MapViewAnnotation : NSObject<MKAnnotation>{}
@property (nonatomic, copy) NSString *title;
@property (nonatomic, readonly) CLLocationCoordinate2D cordinate;
- (id) initWithTitle:(NSString *) t coordinate:(CLLocationCoordinate2D) c;
@end
和实施:
#import "MapViewAnnotation.h"
@implementation MapViewAnnotation
@synthesize title;
@synthesize coordinate;
- (id) initWithTitle:(NSString *) t coordinate:(CLLocationCoordinate2D) c{
self = [super init];
self.title = t;
self.coordinate = c;
return self;
}
@end
这是UIViewController
:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
@interface ViewController : UIViewController <CLLocationManagerDelegate,MKMapViewDelegate>{}
@property (nonatomic, strong) IBOutlet MKMapView *mapView;
@property (nonatomic, strong) CLLocationManager *locationManager;
@end
和.main
文件:
#import "ViewController.h"
#import "MapViewAnnotation.h"
@interface ViewController () @end
@implementation ViewController
@synthesize mapView, locationManager;
- (void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.mapView.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.mapView setShowsUserLocation:YES];
CLLocationCoordinate2D location;
location.latitude = 37.78608;
location.longitude = -122.405398;
MapViewAnnotation *mapAnnotation = [[MapViewAnnotation alloc] initWithTitle:@"Store location" coordinate:location];
[self.mapView addAnnotation:mapAnnotation];
}
-(void) mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views{
MKAnnotationView *annotationView = [views objectAtIndex:0];
id<MKAnnotation> mp = [annotationView annotation];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate], 250, 250);
[self.mapView setRegion:region animated:YES];
}
@end
它成功显示了我当前的位置,但是当我在 viewDidLoad 中使用这一行时:
MapViewAnnotation *mapAnnotation = [[MapViewAnnotation alloc] initWithTitle:@"Store location" coordinate:location];
我得到这个例外:
MapKitDemo[3426:c07] -[MapViewAnnotation setCoordinate:]: unrecognized selector sent to instance 0x8551ae0
2012-10-03 16:19:23.070 MapKitDemo[3426:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MapViewAnnotation setCoordinate:]: unrecognized selector sent to instance 0x8551ae0'
我究竟做错了什么?