Question

I am working on a simple application that gathers a users current data in a location model. That is working and I can log the locations. However, no viewControllers are seeing the updated variable. I am using KVO in the viewControllers to fire but it seems that CLLocation does not send using 'NSKeyValueObservingOptionNew'. It will fire if I use the 'NSKeyValueObservingOptionInitial' but this fires before the CLLocationManager has had an opportunity to set the instance.

Does anyone know why CLLocation is not sending the "...New" value? Like I said, it is working only when it is set to the "...Initial" state.

Thoughts?

View Controller Code:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if ([keyPath isEqual:@"locationUpdated"]) {

        CLLocation *locationVariable = [[CLLocation alloc]init];
        locationVariable = self.location.currentLocation;
        NSLog(@"the location vaiable: %@", locationVariable);
        self.theMap.centerCoordinate = self.location.currentLocation.coordinate;

    }
}

Location Model Code:

- (void)startLocationManger {

    if ([self locationManager] == nil) self.locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [_locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    CLLocation *locationFix = [locations lastObject];
    _currentLocation = locationFix;
    NSLog(@"Current Location: %@", _currentLocation);

}
Was it helpful?

Solution

The main reason the KVO notification is not firing from the Location Model code is probably this line in the locationManager:didUpdateLocations delegate method:

_currentLocation = locationFix;

The code is assigning a value directly to the backing variable of the property you want to observe.

Automatic KVO notifications only fire if you use the synthesized property setter:

self.currentLocation = locationFix;  // <-- assign using self.xxx


A bit unrelated but in the observeValueForKeyPath method:

  1. I'm not sure why you're checking if ([keyPath isEqual:@"locationUpdated"]). Are you sure that's the keyPath you want to look for?
  2. In this code:

    CLLocation *locationVariable = [[CLLocation alloc]init];
    locationVariable = self.location.currentLocation;
    

    the alloc+init is unnecessary since the variable is then immediately assigned a new value. Just do:

    CLLocation *locationVariable = self.location.currentLocation;
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top