objective-cautorelease

Leaking objects, and I need to fix it


I'm importing some older ObjC code, circa 2006, to the latest Xcode. It was written before the era of ARC, and I don't have a strong handle on the previous system. Looking for some advice on how to diagnose these.

Here's an example, one of hundreds...

sym = [ globals addObject:[ [ NCObject alloc ] initWithArray:saved dimension:dimension type:type ] ] ;

The error isn't specific, do I need an autorelease around the entire thing, or one immediately after "type ]"?

I seem to recall that the basic rule is that if I see an inti, I need to autorelease it. Are there other cases I need to think about?


Solution

    1. alloc... (any method that starts with alloc), new, copy..., mutableCopy... give you retained objects (thanks to @jlehr for extending the original list).
    2. Collections retain objects that are contained in them (in your case, globals retains that NCObject that you create.
    3. You should balance every retain that you write with a release or autorelease. If you release an object, you can't use it anymore, because if its retainCount has reached zero, it will be deallocated instantly. An autoreleased object will live until the nearest autoreleasepool drain.

    In the example that you wrote, you either have to balance an alloc, so you have to either release your NCObject after you've added it to the array (if you release it before that, it will most likely be deallocated), or autorelease it whenever you want.

    But I would really recommend you to read Apple's Advanced Memory Management Programming Guide. It's short. And it describes all the rules that you'll need.