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.
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.
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.”
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.
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.
No, you don't need to tell each object to be release
d. 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With