开发者

difference between assigning between self. and assigning from ivar directly [duplicate]

开发者 https://www.devze.com 2023-04-08 07:44 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: When to use self on class 开发者_StackOverflow社区properties?
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

When to use self on class 开发者_StackOverflow社区properties?

Difference between self.ivar and ivar?

I know that when you do

self.array = [[NSMutableArray alloc] init];

this means that I am calling the setter method. However, I can also do:

array = [[NSMutableArray alloc] init];

Which is assigning the ivar directly, no setters is called (I assume). Sometimes both cases will have the same effect, sometimes not. So what is the crucial main difference between doing one over the other? Can someone explain this clearly..


If array property is retained then 1st one will cause a memory leak. In that case you are gaining ownership twice in one line, one via alloc and one via retained property. So one release is not enough.

And in 2nd one if you release immediately after alloc then you loose the ownership immediately as you have not retained array in that case.


The crucial difference is that the setter can have additional side effects — such as retaining the argument or issuing KVO notifications — while a simple assignment can't.


The Objective-C Programming Language tells you to use direct access in the initializer:

There are several constraints and conventions that apply to initializer methods that do not apply to other methods:

  • If you set the value of an instance variable, you typically do so using direct assignment rather than using an accessor method. Direct assignment avoids the possibility of triggering unwanted side effects in the accessors.

and in dealloc:

Typically in a dealloc method you should release object instance variables directly (rather than invoking a set accessor and passing nil as the parameter), as illustrated in this example:

- (void)dealloc {
    [property release];
    [super dealloc]; 
}

to avoid, as Chuck said, side effects like KVO notifications.

Example: in my code I have a variable that triggers the preloading of related data in advance. Sometimes I release it or set it to nil to get rid of the variable, which means I don't need to preload anything, so I use direct access. This example is rarely the case, but it doesn't cost you anything to follow this convention.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号