gpt4 book ai didi

ios - observeValueForKeyPath 不起作用

转载 作者:行者123 更新时间:2023-11-29 00:31:39 25 4
gpt4 key购买 nike

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

最佳答案

应该更像这样:

[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

关于ios - observeValueForKeyPath 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41607418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com