Why do @synthesize variable names begin with an _?
我刚开始使用Objective-C,我需要澄清一些事情
当i@合成@property时,通常会执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 | @interface Class : ParentClass @property propertyName @end @implementation @synthesize propertyName = _propertyName; @end |
我已经看到很多问题和答案表明,"属性名"被广泛接受为合成属性的"正确"方法。但是,它有什么作用吗?或者仅仅是为了提高可读性和识别实例变量?
这样做的目的是,如果你不小心离开了"self",你会得到一个很好的编译器错误,而不是默默地不调用你的方法。
来自http://developer.apple.com/library/ios/documentation/cocoa/conceptive/programmingwithobiodic/enclusingdata/enclusingdata.html
You Can Customize Synthesized Instance Variable Names
As mentioned earlier, the default behavior for a writeable property is
to use an instance variable called _propertyName.If you wish to use a different name for the instance variable, you
need to direct the compiler to synthesize the variable using the
following syntax in your implementation:@implementation YourClass @synthesize propertyName =
instanceVariableName; ... @end
也:
Note: The compiler will automatically synthesize an instance variable
in all situations where it’s also synthesizing at least one accessor
method. If you implement both a getter and a setter for a readwrite
property, or a getter for a readonly property, the compiler will
assume that you are taking control over the property implementation
and won’t synthesize an instance variable automatically. If you still
need an instance variable, you’ll need to request that one be
synthesized: @synthesize property = _property;
是的,它提高了可读性,并且还分离了私有和公共变量来理解和使用。类的私有变量通常以"propertyname"格式写入。可以说,它是一种编码约定,其中私有变量名使用""作为前缀,公共变量或属性名使用LowerCamelCase。
通过这样做,生成的访问器实际上知道要使用哪个变量(ivar)。