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

♀尐吖头ヾ 提交于 2019-12-24 00:43:28

问题


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:


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.




回答2:


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



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/3795615/will-this-objective-c-nested-nsarray-cause-a-memory-leak-on-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!