NSMutableArray memory management

后端 未结 5 1027
情歌与酒
情歌与酒 2020-12-09 08:48
NSMutableArray *a1 = [[NSMutableArray alloc] init];
NSMutableArray *a2 = [NSMutableArray array];

TempObj *obj = [[TempObj alloc] init]; //assume this line is repeat         


        
相关标签:
5条回答
  • 2020-12-09 09:05

    The basic thing to remember is this: You must balance every call to "init", "retain" or "copy" with a corresponding call to "release" or "autorelease". That's really all that you need to know.

    In your example, a1 had a call to "init", so you need to have a "release" somewhere on it. Ditto with "obj". You didn't call "init", "retain", or "copy" on anything else, so you don't need to call "release" or "autorelease" on anything else.

    0 讨论(0)
  • 2020-12-09 09:08

    It's easier to think of Objective-C memory management as ownership rather than in terms of retain-release. When you add the objects to the array, the array is now a co-owner of the object and is responsible for properly managing the memory. When the owner (whatever object contains the code you posted) calls release on the objects, it's giving up ownership and now the array is the sole owner.

    Apple has a good primer on how ownership works in Cocoa (including how you know when you are responsible for calling release on an object): Memory Management Programming Guide For Cocoa. It's a must-read if you want to use Cocoa.

    0 讨论(0)
  • 2020-12-09 09:08

    i dont know either im right or wrong

    NSMutableArray *a1 = [[NSMutableArray alloc] init]; // will be autorelease
    NSMutableArray *a1 = [NSMutableArray alloc]; // will not autorelease
    

    after you [a1 removeAllObjects];

    0 讨论(0)
  • 2020-12-09 09:10

    When you add an object to an array, it calls retain on that object. If you don't release your pointer to that object, it will be a leak. When you release the array, it will call release on all of the objects that it holds, since it called retain previously.

    As for autorelease vs release, the only way to know for sure (aside from possibly reading the documentation) is by the name of the method. I believe the rule in general is that if you didn't allocate the object, then you aren't responsible for releasing it.

    Regarding the object creation methods, all of the convenience methods (array:, arrayWithObjects:, arrayWithArray:, etc.) return autoreleased objects. However, their corresponding init methods (init:, initWithObjects:, initWithArray:, etc.) do not - if you call them, you are responsible for calling release on the returned object.

    I seem to recall a few other questions on this topic here - you might try searching around for a more thorough explanation.

    0 讨论(0)
  • 2020-12-09 09:27

    You released obj, obj2, obj3, obj4 just after adding them to the array(best way). Otherwise you'd have to loop and release each object (that's the stupid way : the one I've done till now).

    0 讨论(0)
提交回复
热议问题