Last active
November 19, 2015 15:25
-
-
Save william8th/dd7f317256561ef29c6b to your computer and use it in GitHub Desktop.
Objective-C Instance variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@implementation WHYPerson | |
... | |
// This is generated by the compiler (there is no need to put this line in your code) | |
@synthesize firstName; // Shorter version | |
// The above, according to Apple automatic naming convention for instance variables, | |
// is just doing this (add '_' prefix): | |
@synthesize firstName = _firstName; // Longer version | |
// Again, in most cases, there is no need to write @synthesize anymore as the compiler does | |
// it for you automatically. However, if you'd love to, you can name your own instance variable: | |
@synthesize firstName = _iLoveFancyIVars; // Custom instance variable naming | |
// Can also just use a normal name without an underscore prefix | |
@synthesize firstName = iLoveFancyIvars; | |
/* Some developers might prefer to do this: | |
// @synthesize firstName = firstName; | |
// Yes, this would save the developer having to type "self." every single time but | |
// I strongly recommend against doing this as it confuses other programmers (especially | |
// those who are not familiar with the workings of the Objective-C compiler/beginners to the language). | |
// They might think that [self firstName] == self.firstName == firstName, which, if the getter method is customised, | |
// would not be the case. It would also discourage new programmers to find out what the difference is between | |
// the many variable accessor methods. | |
*/ | |
// And in your methods, you can refer to the variable in a couple of ways | |
- (void)doSomething { | |
NSLog([self firstName]); | |
NSLog(self.firstName); // Just a wrapper for [self firstName] | |
NSLog(_firstName); // Can be done even if you don't put @synthesize as this instance variable is created automatically | |
NSLog(_iLoveFancyIvars); // Can only work if you define a custom instance variable by yourself (line 13) | |
} | |
... | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment