Number 1 is probably correct.
ClassOne *ob = [[ClassOne alloc] init]; // do i should use autorelease here ?
When you call [ClassOne alloc]
you get an object with a retain count of 1 and you are responsible for the release.
self.O = ob;
Assuming self.O
is a retain
property and not an assign
property, self.O
/ob
will have a retain count of 2.
[ob release];
Now self.O
/ob
will have a retain count of 1. This release
matches up with the alloc
. The remaining retain count is owned by self
so you'll have to remember to release O
when self
is finished with it.
-(void)dealloc{
[O release]; // is this correct ??
}
Good. You remembered to release O
. Now O
will be fully released when self
is dealloced. (Note: you should call [super dealloc]
at the end of dealloc
.)
- (void) runIt {
ClassOne *ob = [[ClassOne alloc] init];
[classTwoOb takeParam:ob];
}
You should release ob
after calling takeParam:
. Methods are responsible for retaining objects they want to keep. If takeParam:
stores ob
on classTwoOb
, it should be retained before the method returns. If not, it shouldn't.
Use autorelease
in methods that return objects that they have created. This gives the caller a chance to retain the object if it wants it, or not if doesn't need it for long. The exception to this is methods used to create objects, which should always be called alloc
, new
, or *copy*
, and should return the object with a reference count of 1, making the caller responsible for the release.
To really learn Objective-C memory management, I recommend reading the Memory Management Programming Guide, especially the section on Memory Management Rules.