使用核心位置委派错误

时间:2012-07-26 11:40:34

标签: iphone objective-c delegates core-location

我按照Apple的Core Location文档中的说明设置了自己的位置检索类。

MyCLControl.h

@protocol MyCLControllerDelegate

@required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
@end

@interface MyCLController : NSObject <MyCLControllerDelegate, CLLocationManagerDelegate> {
    CLLocationManager *locationManager;
    id <MyCLControllerDelegate> delegate;
}

@property (nonatomic, retain) CLLocationManager *locationManager; 
@property (strong) id <MyCLControllerDelegate> delegate;

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation;

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error;

- (BOOL) connected;
@end

MyCLController.minitlocationManager:didUpdateToLocation:fromlocation方法:

- (id) init {
    self = [super init];
    if (self != nil) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        //locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    }
    return self;
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    [self.delegate locationUpdate:newLocation];
}

我打电话的方式如下:

- (void)viewDidLoad {
    MyCLController *locationController = [[MyCLController alloc] init];
    locationController.delegate = locationController.self;
    [locationController.locationManager startUpdatingLocation];
}

- (void)locationUpdate:(CLLocation *)location {
    NSLog(@"%@", location);
}

一旦命中[MyCLController locationUpdate:]: unrecognized selector sent to instance,我就会收到运行时错误[self.delegate locationUpdate:newLocation]

1 个答案:

答案 0 :(得分:0)

您已将MyCLController作为自己的代表吗?当然你的意思是让视图成为代表吗?

您还需要使用以下方法检查委托是否支持该方法(即使它是required):

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    if ([self.delegate respondsToSelector:@selector(locationUpdate:)])
    {
        [self.delegate locationUpdate:newLocation];
    }
}