Reputation:
This my first time using KVO in an iOS project and I wanted to observe the changes of my two UILabel's after getting my position by GPS, and keep notifying me. when I run the project I got my 2 labels showing the date and they are changing by time, but observeValueForKeyPath
doesn't work.
@implementation GpsViewController{
CLLocationManager *locationManager;
CLLocation *crnLoc;
}
@synthesize gpsView;
@synthesize gpsModel;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
gpsView = [[GpsView alloc] initWithFrame:CGRectMake(0, 0, widthtScreen,heightScreen)];
[self.view addSubview:gpsView];
[self initLocation];
}
- (void)initLocation
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
[self showAlert];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
crnLoc = [locations lastObject];
NSLog(@"position long : %@",[NSString stringWithFormat:@"%.8f",crnLoc.coordinate.longitude]);
NSLog(@"position lat : %@",[NSString stringWithFormat:@"%.8f",crnLoc.coordinate.latitude]);
gpsView.longitudeLabel.text = [NSString stringWithFormat:@"%.8f",crnLoc.coordinate.longitude];
[gpsView.longitudeLabel addObserver:self forKeyPath:@"long" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
gpsView.latitudeLabel.text = [NSString stringWithFormat:@"%.8f",crnLoc.coordinate.latitude];
[gpsView.latitudeLabel addObserver:self forKeyPath:@"lat" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"long"]) {
NSLog(@"observe1");
}
if([keyPath isEqualToString:@"lat"]) {
NSLog(@"observe2");
}
}
Upvotes: 1
Views: 2930
Reputation: 2918
It should be more like this:
[gpsView.longitudeLabel addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
and in
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context;
your object is the corresponding label, so you could check for
if object == gpsView.longitudeLabel
Upvotes: 2
Reputation: 2800
You can't just create any string inside forKeyPath
. This determines the name of variable you are observing, so you can use for example "text" as forKeyPath
if you want to observe changes in text.
Upvotes: 1