1

可能重复:
self.ivar 和 ivar 之间的区别?

我想知道,如果我在 Obj-C 中定义一个实例变量作为属性,例如,

@property (copy) NSString *str; 

@synthesize str = _str; 

我应该在实例方法中访问它吗

_str = @"ABC";

或者我应该使用访问器,即

[self setStr:@"ABC"];

有没有关于这方面的一般指导方针?

非常感谢!

4

2 回答 2

7

可以从类内部读取实例变量:

NSLog(@"str = %@", _str);

但不要直接设置实例变量:

_str = @"ABC"; // No!

这绕过了copy您在财产上如此小心放置的机制。所以改为这样做:

[self setStr:@"ABC"]; // Ok
self.str = @"ABC";    // Ok, shorter
于 2012-10-17T03:21:30.597 回答
2

I somewhat disagree with @Dietrich in drawing such a hard line. Utilizing property getters and setters are highly effective and provide extra stuff as a benefit such as automatic support for key value coding, however they also have drawback of doing extra stuff. As a practice, no external objects should ever access an objects member variables directly however you have the control and choice of whether to directly access and set the member variables within a class.

PROS for direct access:

1) faster - it may not seem like much but every time you use a method instead of directly access a variable you incur function overhead - do this in a loop and the cost is not insignificant.

2) explicit - you know exactly what is changing when you set the variable

CONS for direct access:

1) Loss of polymorphism on the getter and setter - by accessing the variable directly you lose the ability for subclasses to extend the functionality of those getters and setters which may be undesirable from an OOP perspective (but then again, that could also be a benefit depending on your architecture)

2) Loss of KVO (or at least making it harder) - key value observing can be very cool way to bind the changing of a member variables value to a method callback to cause some sort of event driven change (mostly things like binding a property to a UI layout/display). KVO is not for everyone though.

3) Loss of automatic synchronization (when declared as atomic) - sometimes you need your member variables to be thread safe. This is a major benefit to properties by them removing boiler plate code.

Ultimately, it's up to you as a developer. In practice, I tend to lean toward direct member variable access with the exception of when I am building an object that is to be thread safe OR to be architecturally robust for extension and KVO.

Hope this helps, the choice is yours! :)

于 2012-10-17T03:41:59.493 回答