[英]Why doesn't observeValueForKeyPath trigger in my webView?
[英]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");
}
}
應該更像這樣:
[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
您不能只在forKeyPath
內部創建任何字符串。 這確定了要觀察的變量的名稱,因此,如果要觀察文本的變化,可以將“ text”用作forKeyPath
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.