Maury Markowitz
Maury Markowitz

Reputation: 9283

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?

Upvotes: 0

Views: 86

Answers (2)

FreeNickname
FreeNickname

Reputation: 7814

  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.

Upvotes: 1

danh
danh

Reputation: 62676

Yes. Autorelease is right. The alloc creates an rc=+1 object. Adding it to the array makes it +2. Autorelease will leave it at +1, which is where you want it. Releasing the globals array eventually will bring it back to 0, which is also desired behavior.

For clarity:

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

Note that release is just as good in this case (a little better because it doesn't leave any autorelease pool work for later). Unless the function returns sym, you can release.

Upvotes: 2

Related Questions