views:

36

answers:

2

Being a noob in Iphone dev, just trying to understand.

In the code below, what is happening exaclty?

City *newCity = [[City alloc] init];
newCity.name = @"name";

NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:newCity];

City *getCity = [array objectAtIndex:0];

[city release];
[array release];

when you add an object to the array, does the array do a retain or does it create a whole new instance?

Also when I do a objectAtIndex to retrieve the city. Am I suppose to release it? Im assuming not since I don't own it? Is this how I should think?

Also when I do release on the array, does it iterate through all the object in the array and call a release on those object as well?

+2  A: 

All of your assumptions are correct.

If you think in terms of ownership you'll always be right, (other than some well documented exceptions).

City *newCity = [[City alloc] init]; //newCity is +1
newCity.name = @"name"; //name +1

NSMutableArray *array = [[NSMutableArray alloc] init]; //array +1
[array addObject:newCity]; //new city +1

City *getCity = [array objectAtIndex:0]; //no memory change

[city release]; //assuming this was supposed to be newCity, newCity -1,
[array release]; //array -1, array deallocs, calling release on all its objects, newCity -1, deallocs
Joshua Weinberg
+1  A: 

When you add an object to the array, the array will retain the object.

And you're right that if you use -[NSArray objectAtIndex:idx], the retain count is not incremented, you do not "own" the object that you get, and you don't need to release it. Unless, obviously, you chose to retain it after you got it from the array.

And yes, when the array is deallocated it will release each of the objects in the array. (That's not the same as saying it will release them when you release the array. This happens only when the array is deallocated)

Firoze Lafeer