简体   繁体   中英

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. You can of course generate a var for everything with @synthezise or tell the compiler not to with @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. 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 ). 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 . 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 ). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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