我已经设置了KVO通知来观看UIWebView的某些属性,如此
[webView addObserver:self
forKeyPath:@"canGoBack"
options:NSKeyValueObservingOptionNew
context:NULL];
并且
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
但它永远不会被调用。我错过了什么或UIWebView是不可观察的?
答案 0 :(得分:11)
canGoBack
是readonly
属性:为了使其符合KVO,它必须在其实现中将该属性重新声明为readwrite
,然后通过合成的setter设置该属性。我怀疑canGoBack
只是通过它的ivar设置,它不会通过KVO系统发送通知:
[self setCanGoBack:YES]; // Would notify KVO observers (as long as any reimplementation of automaticallyNotifiesObserversForKey does place restrictions)
_canGoBack = YES; // Would not notify KVO observers
此相关问题详细讨论了该问题:Is it possible to observe a readonly property of an object in Cocoa Touch?
作为一种变通方法,您可以设置UIWebViewDelegate
并检查[UIWebView canGoBack]
中[UIWebViewDelegate webViewDidFinishLoad:]
的值。