views:

18

answers:

2

In Objective-C, is there any way to find out which objects are the ones retaining another object?

For example, I have a collection of MyClass objects and if I iterate through them to get the retain count on each object, I see the count at 2. How can I find out who the holders are?

for (NSString *aKey in aDictionaryOfMyObjects)
{
   MyClassObject *myClassObj = [aDictionaryOfMyObjects objectForKey:aKey];

   // following shows a retain count of 2. Presumably, the first count is 
   // due to myClassObj is held as the value in NSDictionary and second is because I 
   // I just acquired a pointer to it above. I'd like to find out who exactly
   // might have references to myClassObj.
   NSLog(@"retain count = %d", [myClassObj retainCount]);
}
+2  A: 

You can't. You could put a breakpoint action on -retain so you can watch when it is called in real time, or you could use dtrace to achieve the same aim. But you can't work backwards from an object to its retainers.

In general, you should not be relying on counting retains anyway. You should be relying on the rules written in Apple's memory management guidelines for Objective-C.

Graham Lee
To expand on what Graham said: Retain counts are unreliable at best. They give a woefully incomplete picture of the object's memory-management situation. If you're relying on them for anything more than supplementary information, you're going to end up tilting at windmills.
Chuck
The Allocations Instrument can also track all retain/release/autorelease events and will show you exactly where any of them were called. Much easier than dtrace and much more automatic than using the debugger.
bbum
A: 

You can't. And this information should normally be of no importance to you.

Ole Begemann