observeValueForKeyPath在返回到UIViewController时未被调用
我正在跟踪UIProgressView
的进度,并将观察者设置为正在跟踪的属性。observeValueForKeyPath在返回到UIViewController时未被调用
我添加观察者在viewWillAppear
,就像这样:
-(void)viewWillAppear:(BOOL)animated
{
[self addObserver:self forKeyPath:@"progress" options:0 context:nil];
}
当我删除观察者在viewWillDisappear像这样:
-(void)viewWillDisappear:(BOOL)animated
{
[self removeObserver:self forKeyPath:@"progress"];
}
而在observeValueForKeyPath方法我更新了发展观:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if([keyPath isEqualToString:@"progress"])
{
[self.progressView setProgress:self.progress animated:YES];
}
}
现在,当我离开这个viewController
和我返回的observeValueForKeyPath
没有被调用,我没有得到progressView
不断更新。根据以上在此视频显示的代码
的progressView的行为: https://youtu.be/PVRT_Jjtdh4
键值编码(KVC)可以间接地访问对象的属性的机制。在你的情况下,“进展”是UIProgressView
的财产。但是,您注册了不具有“进度”属性的UIViewController
对象的观察者。
因此与self.progressView
[self addObserver:self.progressView forKeyPath:@"progress" options:0 context:nil];
更换self
到
[self addObserver:self.progressView forKeyPath:@"progress" options:0 context:nil];
而且,分离观察者做同样的:
[self removeObserver:self.progressView forKeyPath:@"progress"];
这不是问题所在。问题是当我离开视图并返回时,不会调用observeValueForKeyPath,并且进度视图不会更新。但是,我不留下看法,一切顺利。 – abnerabbey
用示例查找更新的答案。这将帮助您:
在这里您必须注册为相对于接收器的关键路径的值的观察者。你也需要设置选项。
用途:
-(void)viewWillAppear:(BOOL)animated
{
[[Receiver Instance] addObserver:self forKeyPath:@"progress" options:NSKeyValueObservingOptionNew
context:nil];
}
-(void)viewWillDisappear:(BOOL)animated
{
[[Receiver Instance] removeObserver:self forKeyPath:@"progress"];
}
休息是因为它是。 这里,[Receiver实例]是您为定义的对象进度正在改变的类的实例。
他们实际上有 – abnerabbey
试试这个答案。这将解决问题。 –
只有在课程被释放后才能更好地移除观察者。所以intsead在viewWillDisappear:animated:
放置,你可以下同:
-(void) dealloc {
[self removeObserver:self forKeyPath:@"progress"]
[super dealloc];
}
你的代码似乎本身来观察你的viewController,其中有没有必要使用KVO。如果你没有离开视图,那么这是预期的,你的进度视图将被更新。什么混淆了人,在这种情况下,当你离开它的所有者时,你必须关注你的progressView,因此viewController。另一方面,如果progressView是viewController的外部视图,那么需要观察viewController的是progressView本身。 – Lane