问题
I search some documentation, and tried Xcode and AppCode. But I'm still uncertain about few things. So can somebody clarify me:
If I have property named foo, should I have private instance variable named
_foo
orfoo
?If I dont't create a private instance variable, just syntetize it. Then what variable should I try to access
self->foo
orself->_foo
?
I have seen both approaches and both worked so I'm curious if there is any coding rules or conventions for this because I didn't find any.
Note: I'm not interested in @synthetize foo=_foo
;
回答1:
1. If I have property named foo, should I have private instance variable named _foo or foo?
You don't have to create the instance variable yourself. A instance variable, prefixed with an underscore will automatically be created for you. Since you shouldn't access the variable directly (see below) you shouldn't care about what the underlying variable is called.
2. If I dont't create a private instance variable, just syntetize it. Then what variable should I try to access self->foo or self->_foo ?
Niether. The idea of the property is to use the accessors instead of direct access to the variable. You should use self.foo
to get and set the property (or [self foo]
and [self setFoo:newFoo];
if you dislike the dot-syntax). Also note that you don't have to explicitly synthesize the property.
回答2:
When Xcode auto-synthesizes a property, it automatically adds a supporting instance variable that has the same name as the property with a prepended _
. You don't need to manually specify the instance variable, it's automatically there.
Although self->_foo
compiles and seems to work, I have never seen anybody using this syntax to access ivars. I find it potentially confusing with the property syntax self.foo
, so I would avoid this notation completely. You can access the instance variable by directly typing _foo
if you want. But I would also avoid that, unless you are overriding or extending a property accessor method.
I would access the property solely through the property dot notation [1], which IMHO makes code more readable and handles the strong/weak/copy semantics that you specified when declaring the property.
- Using property dot notation is syntactic sugar for accessing the property through the auto-syhthesized
-(PropertyType)property
and-(void)setProperty:(PropertyType)property
methods
来源:https://stackoverflow.com/questions/17783546/private-variables-which-are-exposed-by-properties