In the Hello World tutorial, I tried to comment out the ‘@synthesize userName = _userName;’ in the HelloWorldViewController.m file. According to https://developer.apple.com/library/mac/#documentation/cocoa/conceptual/objectivec/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW1, “… You use the @synthesize directive to tell the compiler that it should synthesize the setter and/or getter methods for a property if you do not supply them within the @implementation block.”
The strange thing to me is that even with ‘@synthesize userName = _userName;’ commented out, the later appearance of statements in the HelloWorldViewController.m file, such as [self.userName length] and self.userName = [[self textField] text], is not considered to be an error or warning by Xcode (I am on V4.4.1). How is this possible?
As I understood, if @synthesize is missing for a declared property, the property is not even defined. What’s more is no @synthesize means no getter or setter method for the property implemented. How come the Hello World app still compiles and runs perfect?
Part of code is here:
#import "HelloWorldViewController.h"
@implementation HelloWorldViewController
//@synthesize userName = _userName;
@synthesize label;
@synthesize textField;
...
- (IBAction)changeGreeting:(id)sender {
[self setUserName:[[self textField] text]];
if([self.userName length]==0){
[self setUserName: @"World"];
}
NSString *greeting=[[NSString alloc] initWithFormat:@"Hello, %@!", self.userName];
self.label.text=greeting;
- (IBAction)changeGreeting:(id)sender {
self.userName = [[self textField] text];
if([self.userName length]==0){
[self setUserName: @"World"];
}
NSString *greeting=[[NSString alloc] initWithFormat:@"Hello, %@!", self.userName];
self.label.text=greeting;
}
@end
Xcode gives no warning or error for the code above.
As of Xcode 4.4 properties are automatically synthesized. If you declare a property that is readwrite and you don’t implement the getter and the setter method for that property, Xcode will insert
@synthesize property = _propertyautomatically for you. For readonly properties you mustn’t implement the getter method to get this behavior.If you implement the setter and/or getter method Xcode will not synthesize the property automatically and won’t create an iVar for you, either. In that case you can still add the
@synthesizeyourself.