observeValueForKeyPath不起作用

时间:2017-01-12 07:30:27

标签: ios objective-c key-value-observing

这是我第一次在iOS项目中使用KVO,我想通过GPS获取我的位置后观察我的两个UILabel的变化,并不断通知我。当我运行项目时,我得到了显示日期的2个标签,它们随时间变化,但observeValueForKeyPath不起作用。

@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");
    }
}

2 个答案:

答案 0 :(得分:1)

应该更像这样:

[gpsView.longitudeLabel addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

并在

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context;

您的对象是相应的标签,因此您可以检查

if object == gpsView.longitudeLabel

答案 1 :(得分:0)

您不能在forKeyPath内创建任何字符串。这确定了您正在观察的变量的名称,因此如果您想观察文本中的更改,可以使用“text”作为forKeyPath