Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If explicitly implement a getter, is the ivar still created?

I am trying to understand all scenarios about properties, mostly when an ivar is automatically created and when it is not. Please tell me if I am correct in my following scenarios:

  1. A property is implicitly readwrite. If a readwrite property is declared, and the getter and setter are both implemented explicitly, is it true that there will be no ivar automatically generated?

  2. Say another readwrite property is declared, and this time only the getter is explicitly implemented. The ivar will be automatically generated because it will be automatically generated as long as one of the two (getter or setter) of the property is not explicitly implemented.

  3. Basically the same as scenario 2, except this time it is the setter that is explicitly implemented. The ivar will be automatically generated because it will be automatically generated as long as one of the two (getter or setter) of the property is not explicitly implemented.

And just to clarify, when the ivar is created, will it always have a preceding underscore "_"?

like image 406
user3451821 Avatar asked Dec 06 '25 14:12

user3451821


1 Answers

All your statements are correct (assuming that you don't explicitly provide a @synthesize statement).

Reference: "Encapsulating Data" in the "Programming with Objective-C" documentation:

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;
like image 199
Martin R Avatar answered Dec 08 '25 05:12

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!