Managing arrays in Objective-C

I have come to find that managing memory when coding in Objective-C is quite an art form. Knowing when to call retain on an object, knowing when to release at the correct time and not crashing the App seems to be a little easier said than done. With that in mind, I had been wondering the best way to go about releasing objects in memory that where being put into an array. Part of the problem was that I wasn't sure exactly how Arrays in the Cocoa framework handled releasing. My original solution was kinda lame, but when something like this.




- (void) SomeMethod {

// _array is a global NSMutableArray in the particular class

_array = [[NSMutableArray alloc] init];



[_array addObject: someObject];

[_array addObject: anotherObject];

}



- (void) dealloc {

int objCount = 0;



// This would release all the objects in the array

while(objCount < [array count]) {

[[_array objectAtIndex: objCount] release];

objCount++;

}



// Release our array object

[_array release];

[super dealloc];

}





I find this to be kind of sloppy. After I did some research, I found that addObject: does a retain on the object in the array, so we can release it after we add it to the array without having to worry about it vanishing from memory before the array is done with it. Much cleaner.





- (void) SomeMethod {

_array = [[NSMutableArray alloc] init];



// addObject puts its own retain on the object, we dont need to worry about it anymore.

[_array addObject: someObject];

[someObject release];



[_array addObject: anotherObject];

[anotherObject release];

}



- (void) dealloc {

// Release our array object, the array will send a release to all its objects as well, bringing its reference count down to zero, and then they will be properly deallocated

[_array release];

[super dealloc];

}



------------------------------------------------------

Comments

Leave a Comment

Name (optional)

Website (optional)




(c) Copyleft 1999-2008, Anthony Lineberry > dtors.org