I’m new to iOS development and I’ve been seeing the following in several tutorials as well as when Xcode autogenerates code for me when subclassing one of my classes. Let’s say I have the following .h and .m files
#import <UIKit/UIKit.h>
@interface Class : NSObject {
NSArray *_infos;
NSString *_context;
}
@property (nonatomic, retain) NSArray *infos;
@property (nonatomic, retain) NSString *context;
@end
#import "Class.h"
@implementation Class
@synthesize infos = _infos;
@synthesize context = _context;
@end
And then consider this which is how I would normally do it:
#import <UIKit/UIKit.h>
@interface Class : NSObject {
NSArray *infos;
NSString *context;
}
@property (nonatomic, retain) NSArray *infos;
@property (nonatomic, retain) NSString *context;
@end
#import "Class.h"
@implementation Class
@synthesize infos;
@synthesize context;
@end
What is the difference? From the notation I can just infer that they’re just declaring the variables as private, but how does it work? If I’m correct.
It’s a silly naming convention. Use it if you want to, leave it if you don’t.
The advantage is that a method argument/local variable named
contextdoes not conflict with the ivar_context. It has little to do with privacy, since you can just specify @private to make the ivars private (or just@synthesizethem in the first place).The disadvantage is that you have underscores everywhere, and underscores are occasionally a bit special in C (though an underscore followed by a lowercase letter is only reserved in file scope, so you should be fine provided the ivar starts with a lowercase letter…). Where necessary, I stick an underscore at the end which feels less dirty.
Sidenote: A few people use method names beginning with an underscore to mean “private”, but this convention is reserved by Apple.