简体   繁体   English

那“每个财产都有支持变量”是真的吗?

[英]Is that “every property have a backing variable” true?

I read that from this book 我从这本书中读到了 在此处输入图片说明

but I also read that in some circumstances property will not generate instance variable automatically. 但我也读到,在某些情况下,属性不会自动生成实例变量。 在此处输入图片说明

So, if that is true, where did property store its value? 那么,如果这是真的,那么财产在哪里存储了价值呢?

That 1st sentence standing by itself is wrong. 第一句本身是错误的。 It should say like... "In most cases, a property is backed by a member variable. 它应该说...“在大多数情况下,属性由成员变量支持。

Valid exceptions are what the second sentence claims. 第二句声称是有效的例外。 It is true. 是真的。


Obviously the 2nd sentence is talking about auto-sythensis. 显然,第二句话是在谈论auto-sythensis。 You can of course generate a var for everything with @synthezise or tell the compiler not to with @dynamic 您当然可以使用@synthezise为所有内容生成一个变量,也可以使用@dynamic告诉编译器不要这样做

The second paragraph you posted is true. 您发布的第二段是正确的。 An instance variable will only be automatically synthesized if the compiler is responsible for at least on of the getter/setter methods. 仅当编译器至少负责getter / setter方法中的一个时,实例变量才会自动合成。 If you decide to override both methods and still want there to be an instance variable that goes with the property you created, you need to manually synthesize it, like this: 如果您决定覆盖这两种方法,并且仍然希望有一个与您创建的属性一起使用的实例变量,则需要手动进行合成,如下所示:

@synthesize variableName;

Notice that if you use the @synthesize clause as is (without the '='), the instance variable that will be created will be by the exact same name (in this case, variableName ). 请注意,如果按原样使用@synthesize子句(不带'='),则将创建的实例变量将具有完全相同的名称(在本例中为variableName )。 If you would like to give the instance variable a different name than the property you created, you can add any name you want like this: 如果您想为实例变量赋予与创建的属性不同的名称,则可以添加所需的任何名称,如下所示:

@synthesize variableName = someOtherName;

In this case, the property name will be variableName and the instance variable name will be someOtherName . 在这种情况下,属性名称将为variableName ,而实例变量名称将为someOtherName The convention is to name the instance variable the same name as the property, only have an underscore at the beginning (in this case _variableName ). 约定是将实例变量命名为与属性相同的名称,仅在开头加下划线(在本例中为_variableName )。 This will also be the variable name if you allow the compiler to create the variable for you, but having it responsible for at least one of the getter/setter methods. 如果允许编译器为您创建变量,但又让它负责getter / setter方法中的至少一个,则它也是变量名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM