简体   繁体   中英

Will this Objective-C, nested NSArray cause a memory leak on iPhone?

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 alloc ing NSArray s within an NSArray , will the nested arrays get released when I call [lines release]; ?

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];

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.

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM