I just want confirmation on whether or not the following causes a memory leak.
.h file
@property (nonatomic, retain) MyObject *foo;
.m file
@synthesize foo;
...
self.foo = [[MyObject alloc] init];
dealloc
is setup as
[foo release];
My understanding is that the implementation of the auto-generated accessor method looks like
-(void)setFoo:(MyObject *)newObject {
if (foo != newObject) {
[foo release];
foo = [newObject retain];
}
}
Walking through self.foo = [[MyObject alloc] init];
now reads to me as, "allocated a new MyObject object whose retain count will be 1, pass it to setFoo:
, foo will never be equal to myObject as it was newly allocated, so release the old value, increment the retain count of newObject making it 2 and assign it to foo"
dealloc releases foo therefore setting its retain count to 1, which means this object is leaked?
To do this safely we should write our code like
self.foo = [[[MyObject alloc] init] autorelease];
Is my understanding correct?
EDIT
I realize this question is not really appropriate for SO, so feel free to point me to a better place to ask this type of question as well.