In Objective-C, what is the difference between calling an object with the underscore (calling instance variable) or calling it with the self
keyword? As an example, I setup a simple .h
and .m
file called Methods
that inherits from NSObject.h
.
Contents of Methods.h
#import <Foundation/Foundation.h>
@interface Methods : NSObject
@property int firstNumber;
@property int secondNumber;
@end
Contents of Methods.m
#import "Methods.h"
@implementation Methods
- (instancetype)init
{
self = [super init];
if (self) {
_firstNumber = 33;
self.secondNumber = 67;
NSLog(@"The value of _firstNumber is: %i", _firstNumber);
NSLog(@"The value of self.secondNumber is: %i", self.secondNumber);
}
return self;
}
@end
This is the result in the command line when this code is executed:
2014-07-07 20:22:08.551 CommandLine[2771:39622] The value of _firstNumber is: 33
2014-07-07 20:22:08.552 CommandLine[2771:39622] The value of self.secondNumber is: 67
This is the expected result, as the values have the numeric value that they were set to, and I've developed using both the underscore and the self
keyword to call and set objects, so what makes one better than another? Or is it a case of personal preference and custom?