9

I've set up KVO notification to watch some properties of a UIWebView like so

[webView addObserver:self 
          forKeyPath:@"canGoBack"
             options:NSKeyValueObservingOptionNew
             context:NULL];

and have

- (void)observeValueForKeyPath:(NSString *)keyPath 
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context

but it never gets called. Am I missing something or is UIWebView just not observable?

iain
  • 5,660
  • 1
  • 30
  • 51
  • The reference docs do not state that UIWebView is KVO compliant, so I would assume that it is not. – aroth Nov 16 '11 at 01:26
  • Ok, thanks. That's what I thought might be the case, but I'd seen some people on here suggest it was. – iain Nov 16 '11 at 11:52

1 Answers1

11

canGoBack is a readonly property: in order for it to be KVO compliant it would have to redeclare that property as readwrite in its implementation and then set the property via a synthesised setter. I suspect that instead canGoBack is just set via its ivar, which would not send a notification via the KVO system:

[self setCanGoBack:YES]; // Would notify KVO observers (as long as any reimplementation of automaticallyNotifiesObserversForKey does place restrictions)
_canGoBack = YES; // Would not notify KVO observers

This related question discusses the issue in detail: Is it possible to observe a readonly property of an object in Cocoa Touch?

As a workaround, you could set a UIWebViewDelegate and check the value of [UIWebView canGoBack] in [UIWebViewDelegate webViewDidFinishLoad:].

Community
  • 1
  • 1
sam-w
  • 7,478
  • 1
  • 47
  • 77
  • 6
    While it might be correct that `UIWebView` is not KVO compliant regarding `canGoBack` your explanation is not. It is definitely possible (and common) to implement readonly properties that are observable (see NSOperationQueue's `operations` for example). Observability has nothing to do with readwrite/readonly. The correct answer would have been that nothing is observable unless the documentation explicitly says so. – Nikolai Ruhe Nov 06 '12 at 10:02
  • 2
    Which part of my answer is incorrect? "Observability has nothing to do with readwrite/readonly": agreed, which is why I explain how a property being `readonly` can indirectly affect observability. – sam-w Nov 06 '12 at 10:12
  • 1
    I downvoted because I think your answer is misleading: You do not state the most important fact that observability has to be documented and cannot be somehow deducted from the interface. – Nikolai Ruhe Nov 06 '12 at 10:52
  • 1
    Cool, go ahead and submit your own answer then :) – sam-w Nov 06 '12 at 10:58
  • 3
    Hm, I agree, this is slightly misleading. It's a shame that `canGoBack` is not observable, but it is *not at all* because it's a readonly property. It's just not observable, the "why" of it is hidden behind UIWebView's implementation. – colinta Mar 03 '14 at 21:51