objective-cmemory-managementautoreleaseretaincount

What do you think about this code in Objective-C that iterates through retain count and call release every iteration?


I'm still trying to understand this piece of code that I found in a project I'm working on where the guy that created it left the company before I could ask.

This is the code:

-(void)releaseMySelf{
    for (int i=myRetainCount; i>1; i--) {
        [self release];
    }
    [self autorelease];
}

As far as I know, in Objective-C memory management model, the first rule is that the object that allocates another object, is also responsible to release it in the future. That's the reason I don't understand the meaning of this code. Is there is any meaning?


Solution

  • The author is trying to work around not understand memory management. He assumes that an object has a retain count that is increased by each retain and so tries to decrease it by calling that number of releases. Probably he has not implemented the "is also responsible to release it in the future." part of your understanding.

    However see many answers here e.g. here and here and here.

    Read Apple's memory management concepts.

    The first link includes a quote from Apple

    The retainCount method does not account for any pending autorelease messages sent to the receiver.

    Important: This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method. To understand the fundamental rules of memory management that you must abide by, read “Memory Management Rules”. To diagnose memory management problems, use a suitable tool: The LLVM/Clang Static analyzer can typically find memory management problems even before you run your program. The Object Alloc instrument in the Instruments application (see Instruments User Guide) can track object allocation and destruction. Shark (see Shark User Guide) also profiles memory allocations (amongst numerous other aspects of your program).