Of your three examples, _foo1
and _foo3
are both instance variables (ivars) and are functionally equivalent (though there are some old compilers that that didn’t permit ivars in the @implementation
). I’ve seen people argue passionately for the @implementation
pattern, your _foo3
example. See the somewhat dated Where to put iVars in “modern” Objective-C? But I prefer to define my ivars in the private extension (your _foo1
pattern), to keep properties and ivars together. But, I’ll leave it there as it’s a matter of personal opinion (and therefore not appropriate for SO).
The second pattern, foo2
, is a property, and is a whole different kettle of fish: Regarding properties vs ivars, Apple advises using properties rather than ivars. In fact, they start the You Can Define Instance Variables without Properties section of the Encapsulating Data chapter of the Programming with Objective-C with the caveat, “It’s best practice to use a property on an object any time you need to keep track of a value or another object.”
Some will argue for ivars over properties for their theoretical performance benefit, but that seems like premature optimization to me, sacrificing code maintenance for negligible performance difference. The advantage of the property is that you can enjoy automatic memory semantics (copy
vs strong
vs weak
) and your code using the property is abstracted away from any special implementation details of the property, were there any.
If you’re looking explanations “in detail”, I’d suggest you refer to the aforementioned Programming with Objective-C guide.
0
solved What’s the difference in these three variable definition?