Chris Wagner
Chris Wagner

Reputation: 21003

Setting property to newly alloc'd object using accessor cause memory leak

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.

Upvotes: 2

Views: 396

Answers (3)

adubr
adubr

Reputation: 777

And another common pattern:

MyObject *newFoo = [[MyObject alloc] init];
self.foo = newFoo;
[newFoo release];

Upvotes: 3

timthetoolman
timthetoolman

Reputation: 4623

you could do that. Alternatively, since we know the setter automatically retains, we could do the following rather than autorelease:

foo=[[MyObject alloc] init];

Which you choose may be a matter of coding style. If you are trying to get the hang of using self.foo, then by all means use your method for the sake of consistency and bug fixing. If you are comfortable with using the dot syntax then use the latter.

Upvotes: 3

Eric Petroelje
Eric Petroelje

Reputation: 60498

Yes, that is absolutely correct.

Upvotes: 5

Related Questions