Setting property to newly alloc'd object using

2019-02-15 14:47发布

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.

3条回答
疯言疯语
2楼-- · 2019-02-15 15:35

Yes, that is absolutely correct.

查看更多
Deceive 欺骗
3楼-- · 2019-02-15 15:51

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.

查看更多
爷的心禁止访问
4楼-- · 2019-02-15 15:51

And another common pattern:

MyObject *newFoo = [[MyObject alloc] init];
self.foo = newFoo;
[newFoo release];
查看更多
登录 后发表回答