在 Hello World 教程中,我尝试注释掉“@synthesize userName = _userName;” 在 HelloWorldViewController.m 文件中。根据https://developer.apple.com/library/mac/#documentation/cocoa/conceptual/objectivec/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW1,“......你使用@synthesize 指令告诉编译器,如果您不在@implementation 块中提供属性,它应该为属性合成setter 和/或getter 方法。”
对我来说奇怪的是,即使使用 '@synthesize userName = _userName;' 注释掉之后,HelloWorldViewController.m 文件中出现的语句,例如 [self.userName length] 和 self.userName = [[self textField] text],不会被 Xcode 认为是错误或警告(我是在 V4.4.1 上)。这怎么可能?
据我了解,如果声明的属性缺少@synthesize,则甚至没有定义该属性。更重要的是没有@synthesize 意味着没有实现属性的getter 或setter 方法。为什么 Hello World 应用程序仍然可以完美编译和运行?
部分代码在这里:
#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 对上面的代码没有给出警告或错误。