I am a new Objective-C programmer and sometimes confused with those ownership concepts of this language….currently i am learning the iPhone programming….
Here are case those confused me always..
i use normally these (sometimes first and sometimes other)
NSMutableArray *array; //Declared in header
case 1
array1= [databaseClass getData];
Case 2
array1 = [NSMutableArray arrayWithArray:[databaseClass getData]];
Here [databaseClass getData] returns a nonAutoreleased array of objects..
I just want to conforms that is anyone of them is correct ?
and if not then please suggest the correct one….
EDIT
I mean to say that [databaseClass getData] already returning me an allocated array (i means a non-autoreleased array) now i think i do not need to allocate my array if i want to use it in my class (i have tested this and it works) , here my only question is about that array1 initialization….Does anyone of those above statements make any sense……if no then i request that please provide a block of code so that it becomes more clear to me…..
Thank You
Both cases should give you an autoreleased object. You’re the owner if:
alloc.copy, as inmutableCopy(the returned copy belongs to you, not the object on which you called thecopymethod).retained it.In all other cases you can assume that you are not the owner and that you do not need to release the object.
So if your
getDatamethod does not return an autoreleased object you should modify it so it does. Otherwise other people using this code will create memory leaks (and you’re likely to confuse yourself this way).Edit after question got edited:
According to the naming convention in Objective-C, the
getDatamethod should return an autoreleased object. So it should be edited to return an autoreleased object if it doesn’t already.If you want to edit the array you do need to make a mutable copy from it. You can either call
[NSMutableArray arrayWithArray:[databaseClass getData]];or[[databaseClass getData] mutableCopy]. In the first case, the array is autoreleased, you are not the owner and you do not need to callreleaseon it. In the second case, you are the owner (as per thecopyrule) and need to release it later on.