开发者

Objective C Array and Object Release

开发者 https://www.devze.com 2022-12-22 23:14 出处:网络
I have a newbie question regarding when to release the elements of a NSArray. See following pseudo code:

I have a newbie question regarding when to release the elements of a NSArray. See 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 rel开发者_JAVA百科ease];
  }

  [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 release the "array" object, do I need to release each of its element (MyObject) first?

I am new to Objective C. Please help. thanks.


No, you don't need to tell each object to be released. When you send a release method to an NSArray, it automatically sends a release method to each item inside first.

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


You don't need to release the kept objects. NSArray retains them when you add, and releases them when released. So if you allocate, add to the array, then release, the object in the array will have the retain count of 1. Once the array is freed, the object is released, therefore freed.


When an object is created, it has a retain count of 1. Whenever a object is added to an array, its retain count is increased (in this case to 2). After adding to the array, your code release its hold of the object, dropping its retain count by 1 (to 1 in this case). Then when you release the array, it calls release on everything in it dropping their retain counts by 1 (to 0 in this case). When retain count hits 0 the object is deallocated.

Your code looks correct from a memory management stand point.

0

精彩评论

暂无评论...
验证码 换一张
取 消