Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C Array and Object Release

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

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

like image 678
david Avatar asked Mar 12 '10 18:03

david


People also ask

What is release in Objective-C?

The system that Objective-C uses is called retain/release. The basic premise behind the system is that if you want to hold on to a reference to another object, you need to issue a retain on that object. When you no longer have a use for it, you release it. Similar to Java, each object has a retain count.

What is the difference between an array and a set in Objective-C?

One of the biggest differences between an Array and a Set is the order of elements. The documentation describes this as well: Array: “An ordered, random-access collection.” Set: “An unordered collection of unique elements.”

What method is automatically called to release objects in Objective-C?

The NSArray class method array returns a newly initialized array that is already set for autorelease. The object can be used throughout the method, and its release is handled when the autorelease pool drains. At the end of this method, the autoreleased array can return to the general memory pool.

How do you declare an array of objects in Objective-C?

To declare an array in Objective-C, we use the following syntax. type arrayName [ arraySize ]; type defines the data type of the array elements. type can be any valid Objective-C data type.


1 Answers

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.

like image 96
Chris Long Avatar answered Oct 05 '22 20:10

Chris Long