为什么Xcode 4自动生成实例变量? [英] Why does Xcode 4 auto-generate a instance variable?
问题描述
我来自C#开发,刚开始学习Objective-C和Xcode 4.
据我所知,@synthesize正在替换属性的getter / setter方法,如果你不需要检查/控制正在读取或写入的值。
I'm coming from C# development and just started to learn Objective-C and Xcode 4. As far as I understand "@synthesize" is replacing getter/setter methods for properties if you don't need to check/control the values which are being read or written.
但为什么Xcode 4会自动为我创建一个实例变量?
But why does Xcode 4 create a instance variable for me automatically?
这还不够:
@synthesize myProperty;
而不是:
@synthesize myProperty = _myProperty;
?
我为什么要这样做?如果我没有/需要任何getter或setter,请使用/拥有实例变量而不是实际属性?
Why would I want to use/have the instance variable instead of the actual property if I don't have/need any getters or setters?
提前致谢!
MemphiZ
编辑:
我明白了@synthesize正在取代getters / setter但这部分的优点是什么: = _myProperty;
?
如果我可以直接使用myProperty,为什么我想要一个实例变量?如果例如setter检查值的条件,我会理解使用_myProperty。如果我想跳过这个检查,我会使用_myProperty。但是当我使用@synthesize时,我没有一个可以进行检查的setter。那么我为什么要/想要一个实例变量呢?
I understand that @synthesize is replacing getters/setters but what is this part good for: = _myProperty;
?
Why would I want to have a instance variable if I could use "myProperty" directly? I would understand using "_myProperty" if the setter for example would check for a condition of the value. If I then want to skip this check I would use _myProperty. But as I use @synthesize I don't have a setter in place that does some check. So why do I have/want an instance variable then?
答案:
请参阅MattyG帖子中的评论!
See the comments in MattyG's post!
推荐答案
这是一个用于提醒程序员通过setter访问实例变量的约定和自己的吸气剂。所以,如果你正在使用:
This is a convention used to remind the programmer to access the instance variables through the setters and getters with self. So if you're using:
@synthesize myProperty = _myProperty;
然后直接访问变量你必须写:
Then to access the variable directly you must write:
_myProperty = something;
要通过它的setter访问变量,你必须写:
To access the variable through it's setter you must write:
self.myProperty = something;
如果您忘记通过自己访问,则可获益。那么编译器会警告你:
The benefit is that if you forget to access through self. then the compiler will warn you:
myProperty = something; //this won't compile
这也是问题。
这篇关于为什么Xcode 4自动生成实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!