observeValueForKeyPath 不起作用

observeValueForKeyPath doesn't work

这是我第一次在 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");
    }
}

您不能只在 forKeyPath 中创建任何字符串。这决定了您正在观察的变量的名称,因此如果您想观察文本的变化,您可以使用例如 "text" 作为 forKeyPath

应该是这样的:

[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