0

I have encountered a weird problem with key value observing in iOS.

I have an object to which I add observers to monitor download progress:

[inAppProduct addObserver:self forKeyPath:@"progress" options:0 context:nil];

I then implement the method

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

Here the object parameter contains the inAppProduct which was changed. It all works well until the screen is locked during a download (either because of inactivity or manually by pressing the power button). After I unlock the screen the observer method still gets called every time inAppProduct is updated, but the object doesn't contain the new values. In stead it contains the last valueinAppProduct had before the screen lock.

If I add the option NSKeyValueObservingOptionNew while adding the observer the change dictionary actually contains the new updated value, even though the object doesn't.

pajevic
  • 4,607
  • 4
  • 39
  • 73
  • I guess I might be a little confused, what is your goal here, why do you need the object? It sounds like you are accessing the updated value from the object instead of the change dictionary? Is this necessary? – JAManfredi Nov 25 '13 at 14:36
  • Well, I am. The updated property is not the only value I need from the object. And also, since I have multiple instances I need to be able to know which object was modified. So the easiest way is to access the object itself, which should be possible without use of the change dictionary. – pajevic Nov 25 '13 at 18:13
  • KVO seems not that suitable for this problem. Did you consider using a delegate pattern or blocks instead? You could also disable the idle timer to circumvent the state causing trouble – Quxflux Nov 26 '13 at 06:06
  • I really can't see why KVO should be unsuitable here. In fact, the code in question comes from the book **iOS 6 by tutorials** by Ray Wenderlich. And indeed it _does_ work. I'm just experiencing the issue with the screen lock. And disabling the idle timer will not solve the problem as you can still lock the screen manually. – pajevic Nov 26 '13 at 06:55
  • Not positive what your code looks like but does it possibly have anything to do with keeping weak references to your object? I know KVO states... Note: The key-value observing addObserver:forKeyPath:options:context: method does not maintain strong references to the observing object, the observed objects, or the context. You should ensure that you maintain strong references to the observing, and observed, objects, and the context as necessary. – JAManfredi Nov 26 '13 at 13:48

0 Answers0