views:

114

answers:

4
NSArray *tLines = [[NSArray alloc] initWithObjects:
                   [[NSArray alloc] initWithObjects:@"Matt", @"David", nil],
                   [[NSArray alloc] initWithObjects:@"Bob", @"Ken", nil], nil];
self.lines = tLines;
[tLines release];

I'm allocing NSArrays within an NSArray, will the nested arrays get released when I call [lines release];?

+1  A: 

I'm pretty sure it will leak, unless you release each object yourself before clearing the Array...

Or try using autorelease option at the creation, it'll do the work for you...

TheSquad
+3  A: 

Why don't you use a convenience method? No need to release memory.

NSArray *tLines = [NSArray arrayWithObjects:
                   [NSArray arrayWithObjects:@"Matt", @"David", nil],
                   [NSArray arrayWithObjects:@"Bob", @"Ken", nil], nil];
Jamie Chapman
I wanted to be explicit about memory management, but I guess I'll do that since it leaks how it is now. Thanks!
MattDiPasquale
+2  A: 

Yes, this will cause a leak.

When created, the sub-arrays have a retain count of 2 (from alloc and adding to the array). When tLines is released, this is decremented to 1; which isn't enough to cause it to be deallocated; meaning that they leak.

Use +[NSArray arrayWithObjects] or autorelease the arrays on creation.

Remember: NARC (New, Alloc, Retain, Copy) should always be balanced with a release or autorelease.

Williham Totland
this isn't quite correct; they have a retain count of (at least) 1 due to `alloc` which is then upped to (at least) 2 by their containing array. when the container is released they fall back to 1. if they did fall back to 0, they would get deallocated.
zem
http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmObjectOwnership.html#//apple_ref/doc/uid/20000043-SW2
zem
I stand corrected.
Williham Totland
+1  A: 

No, you should not do this. When you alloc the arrays, you need to release them. The containing array will handle memory management for its objects (retaining them when they're added, releasing when they're removed), but that is beside the responsibility of the object that created to the arrays to properly release them. You should either use a convenience constructor to create the arrays or else create them one at a time and release them after they've been added to the master array.

Chuck
Thanks. So, what i'll do is use `initWithObjects` for the master array and `arrayWithObjects` for its nested arrays, and when I release the master array, there should be no more memory leaks, right?
MattDiPasquale