A subtlety of object identity in Obj-C

2010
02.26

A problem: given an object a of class A that aggregates a publicly accessible instance of class B determine if an instance changed by polling periodically. This comes up often in concurrent systems where an object change warrants a response while KVO is undesirable. The first thought that comes to mind is to a cache the instance of B during each cycle of polling after the comparison of the cached instance to the present value.

Our code might look like this

if (cachedB != [a valueOfB]) { triggerEvent(...); }
cachedB = [a valueOfB];

Unfortunately this fails miserable due to the fact that a newly allocated instance of B may occupy the same memory location as the previous one (assuming, of course, that we never retain the cached value). This is a low probability failure and is extremely hard to debug. This bug is solved by storing a timestamp upon change of instance of B inside a, and cacheing it instead of the memory address.

Your Reply

You must be logged in to post a comment.