Reputation: 8977
So in the guidelines it says:
For code that will run on iOS only, use of automatically synthesized instance variables is preferred.
When synthesizing the instance variable, use @synthesize var = var_; as this prevents accidentally calling var = blah; when self.var = blah; is intended.
// Header file
@interface Foo : NSObject
// A guy walks into a bar.
@property(nonatomic, copy) NSString *bar;
@end
// Implementation file
@interface Foo ()
@property(nonatomic, retain) NSArray *baz;
@end
@implementation Foo
@synthesize bar = bar_;
@synthesize baz = baz_;
@end
Question is, does this apply to public variables only or private too? It's not really clear on the documentation, but would like to have some thoughts or perspective on why "if" this is only for public or private only? I think that it just makes sense for all public/private so that you don't mess up ivars and using the property
Upvotes: 2
Views: 670
Reputation: 1644
I don't think it particularly matters whether the variables in question are public or private. The practice of synthesizing under a different name makes it explicit when you are accessing the variable directly instead of using the generated accessor method.
Perhaps there's a different question underlying what you're asking: should I typically access private ivars via the accessor or directly? I think most skilled iOS devs tend to use accessors unless there is some particular reason not to (performance, avoiding side effects like KVO, etc.). Doing so is more future-proof and allows for flexibility in the underlying implementation. In a very small way, you're coding to an interface rather than an implementation.
It also might be worth pointing out that the default behavior of Clang is going to change in the future so that property-backing ivars are synthesized named _foo
by default. Clearly the powers-that-be consider consider underscoring ivars to be a best-practice.
Upvotes: 1
Reputation: 18253
I am pretty sure much of it comes down to personal preferences, so here are mine, for what they are worth:
I'd agree with Paul.s. that consistency is your friend, but to me, distinction is a friend, too.
Upvotes: 0