C object array and object

I have a newbie question regarding when to release NSArray elements. See the following pseudo code:

NSMutalbeArray *2DArray = [[NSMutableArray alloc] initWithCapacity:10]; for (int i=0;i<10;i++) { NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:5]; for (int j=0;j<5;j++) { MyObject *obj = [[MyObject alloc] init]; [array addObject:obj]; [obj release]; } [2DArray addObject:array]; [array release]; } // use 2DArray to do something [2DArray release] 

My question here is when I release 2DArray, do I need to explicitly release each of its element (array) first? Also, before I let go of the array object, do I need to release each of its elements (MyObject) first?

I am new to Objective C. Please help. Thank you

+7
memory-management arrays objective-c
source share
3 answers

No, you do not need to tell release d to each object. When you submit the release method to NSArray , it automatically sends the release method for each element inside the first.

So, in your case, you send [2DArray release] . This automatically sends [array release] to every other array, which sends [obj release] every object within each array .

+14
source share

You do not need to release saved objects. NSArray saves them when added and releases them when released. Therefore, if you select, add to the array, and then release, the object in the array will have a save counter 1. After the array is released, the object is freed, therefore it is freed.

+4
source share

When an object is created, it has a save counter of 1. When an object is added to the array, its hold amount increases (in this case, to 2). After adding to the array, your code frees its object, discarding its hold amount by 1 (up to 1 in this case). Then, when you free the array, it causes a release on everything that in it lowers their hold amount by 1 (to 0 in this case). When the count count reaches 0, the object is freed.

Your code looks right in terms of memory management.

+2
source share

All Articles