As Objective-C has evolved (I use it exclusively with xcode/ios for iPhone/iPad development), there seems to be many different ways you can layout your class instance variables. Is there a ‘best practice’ way that’s become common consensus? (I realise Apple demo/example code is all over the place in terms of style)
In particular the idea of handling private variables. Here are a number of ways I’ve seen to manage some instance variables for a class (I’ve left out the interface/implementation for brevity) – and I’m not even including the use of underscore named synthesized properties.
.h
@property (nonatomic, strong) NSString *aString;
.m
@synthesize aString;
- (void)aMethod {
aString = @"Access directly, but if I don't have custom getter/setters and am using ARC, do I care?";
self.aString = @"Access through self";
}
Or this:
.h
@property (readonly) NSString *aString;
.m
@property (nonatomic, strong) NSString *aString;
...
@synthesize aString;
Or this:
.m
@interface aClass {
NSString *aPrivateString;
}
- (void)aMethod {
aPrivateString = @"Now I have to access directly, but is this atomic/nonatomic?";
}
I don’t want this question to turn into a style argument, but it seems to me there should be a “if you’re not doing something specific or complex or weird, use this method for defining your class variables” standard.
I’d prefer use the following convention for public and private ivars/properties:
.h
.m
This way everything starting with _ is an ivar (_publicString is the underlying ivar for the property, this prevents me from using publicString while I want to use self.publicString).