Reputation: 3154
I've been using addObserver:forKeyPath:options:context: quite a bit in my code, and have always been setting the "context" part of it to nil. I see plenty of examples where people have used the "context", but have a hard time grasping exactly why. Is it helpful if you have more than one object observing the key, and want to figure out which object should respond when the key changes? If so, is that the only reason?
thanks
Upvotes: 1
Views: 662
Reputation: 17481
The biggest reason to have a unique context is to deal with the situation where a subclass (or superclass) is also observing the same keyPath. If you know that this observation is yours, you can return out of the observer. However, if it belongs to somebody else, you should pass it along to the superclass (if there is any), which might be expecting it.
In the event of another object observing the keyPath, you won't receive the observation message for that object. However, in the case of subclassing, you need to pass on the observation to the superclass, which is where this becomes important.
Another place where I've found it useful is when you need to observe a value change in multiple values and have the identical reaction to them (such as setNeedsDisplay: on some view). In this case, you can give them all the same context, and you only have to check the context, instead of each keyPath.
Upvotes: 3