I know that my question has already been discussed on StackOverflow but i found the answer not complete for my needs. So the question is:
NSMutableArray *firstArray = [[NSMutableArray alloc] initWithObjects: obj1,obj2,nil];
NSMutableArray *secondArray = [[NSMutableArray alloc] init];
secondArray = [firstArray mutableCopy];
what is retain count for the secondArray now? 2 or 1? Should i release it twice or just once?
Does copy or mutableCopy increases retain count of the COPYING (secondArray in this event) object?
You should never care about the absolute retain count. Only that you’re “balanced”, that means for every
alloc,new*,copy,mutableCopyandretainyou need a correspondingreleaseorautorelease(when not using ARC, that is).If you apply this rule to each line you can see that your second line has an
alloc, but there’s no release. In fact, it’s absolutely useless to allocate an instance here since you’re not interested in it anyway. So it should simply read:But let’s discuss your original code and see what happened:
In Objective-C, we often speak of ownership: there are very few methods that make you the “owner” of an object. These are:
allocnew*, as innewFoocopyandmutableCopyretainIf you call these, you get an object for which you are responsible. And that means you need to call a corresponding number of
releaseand/orautoreleaseon these objects. For example, you’re fine if you do[[obj retain] retain];and then[[obj autorelease] release];