I'm trying to learn objective c and I'm still a bit confused with memory management. Yes I know, I should use ARC, but my project uses TouchXML that does not support it. Also there is a lot of documentation and threads about memory management that I have read but I still have some doubt that I hope you guys will help me to clarify.
I've learnt that who allocs an object is then responsible to free it. I've also learnt that "retain" increments the reference counter whereas "release" decrements it. When an object's reference counter reaches 0, it is automatically de-alloced. I've finally learnt that "autorelease" releases the object automatically at the end of current event cycle. That's fine.
Now please consider the following case:
I alloc an array that I need to use for the full lifecycle of my object. I'm responsible to release it when my object is deleted:
@implementation MyClass
-(id) init {
myArray = [[NSMutableArray alloc] init]; // this is a @property
}
- (void) dealloc {
[myArray release];
[super dealloc];
}
@end
In this way, in dealloc method, myArray release also causes myArray o be deallocated. If I then instance a new object from myClass and retain myArray like this...
// MyOtherClass
MyClass *o = [[[MyClass alloc] init] autorelease];
NSMutableArray *retainedArray = [[o.myArray] retain];
...at the end of current event cycle, "o" will be automatically deallocated, whereas retainedArray (actually pointing to o.myArray) will not be deallocated until I'll call [retainedArray release]. Is this correct up to here?
If so, I also guess the same applies if I call something like:
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"somePath" error:nil];
I don't need (actually I can't otherwise it will give a runtime error) call either release or autorelease for "contents" unless I retain it somewhere in my code. Correct?
If so, summing everything up, in the end I only have to call release if I call either alloc or retain. The balance of reference counts in my class should always be 0, where alloc / retains gives +1 and release gives -1. Correct?