alloc + init with synthesized property - does it cause retain count to increase by two?

前端 未结 4 934
生来不讨喜
生来不讨喜 2021-02-05 10:23

I\'ve seeen the following snippet quite a bit:

In the header:

SomeClass *bla;
@property(nonatomic,retain) SomeClass *bla;

In the implem

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 10:34

    It looks like the core problem here is a misunderstanding of object ownership semantics in Cocoa. For every init, copy or retain called on an object a call to release or autorelease must be made. What's happening here is that the call to init doesn't have a matching call to release or autorelease.

    I think what's confusing here is that the dot-notation for property assignment is syntactic sugar for a method call. So it looks like it's just an assignment when in actuality it's a call to a property setter.

    self.bla = [[SomeClass alloc] init];
    

    is not the same thing as:

    bla = [[SomeClass alloc] init];
    

    The former translates into:

    [self setBla: [[SomeClass] alloc] init]];
    

    while the latter is literally an assignment.

    To fix your issue all you really need to do is ensure that the code that calls init calls autorelease so that the retain count will be decremented after the retain call by the setter.

提交回复
热议问题