Determine who is holding onto an object
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 *myClassO开发者_JAVA百科bj = [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]);
}
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.
You can't. And this information should normally be of no importance to you.
精彩评论