简体   繁体   中英

iOS CoreLocation & Singleton pattern: Delegate methods not working

I am creating a CLLocationManager singleton to be used by other objects in my app. For some reason when I call

[locationManager didUpdateLocations]

I get error

no visible @interface declares the selector

I'm new to CoreLocation and haven't gotten it completely figured out yet. Is the problem my LPLocationManager inherits from NSObject and not CLLocationManager or is it something else?

.h

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@interface LPLocationManager : NSObject <CLLocationManagerDelegate>

+(LPLocationManager*)sharedManager;

@property (strong, atomic) CLLocationManager *locationManager;

@end

.m

#import "LPLocationManager.h"

@implementation LPLocationManager

+(LPLocationManager*)sharedManager{
    static LPLocationManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[self alloc]init];
    });
    NSLog(@"CL shared manager returned");
    return sharedManager;
}

- (id)init
{
    self = [super init];
    if (self) {
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 10;
    }
    return self;
}

@end

I made my Core location singleton to be the delegate itself

#pragma  mark - CLLLocation manager delegate
-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation   *)newLocation fromLocation:(CLLocation *)oldLocation
{
    self.currentLocation = newLocation;
}

and in the setter for my public property

@property (strong, nonatomic)CLLocation *currentLocation;

i post notification

- (void)setCurrentLocation:(CLLocation *)currentLocation
{
    if (!_currentLocation) {
    _currentLocation = [[CLLocation alloc] init];
}
_currentLocation = currentLocation;
[[NSNotificationCenter defaultCenter] postNotificationName:@"did update location" object:nil];

}

so that every class that is interested in getting those notifications could become observers of this event:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLocation) name:@"did update location" object:nil];

don't forget to tell your LocationManager to

 [self.locationManager startUpdatingLocation];

Here is an example of using CLLocationManager as singleton. You can find the complete example on GitHub .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM