【问题标题】:I can use a declared property in implementation even without @synthesize it. Is this by design?即使没有@synthesize,我也可以在实现中使用声明的属性。这是设计使然吗?
【发布时间】:2012-08-11 23:35:51
【问题描述】:

在 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 对上面的代码没有给出警告或错误。

【问题讨论】:

    标签: objective-c xcode cocoa-touch


    【解决方案1】:

    从 Xcode 4.4 开始,属性是自动合成的。如果您声明了一个可读写的属性并且您没有为该属性实现 getter 和 setter 方法,Xcode 将自动为您插入 @synthesize property = _property。对于只读属性,您不能实现 getter 方法来获取此行为。

    如果您实现 setter 和/或 getter 方法,Xcode 将不会自动合成属性,也不会为您创建 iVar。在这种情况下,您仍然可以自己添加@synthesize

    【讨论】:

    • 我认为重要的不是 Xcode 的版本,而是底层编译器 LLVM-clang 的版本(功能)。
    • 你是对的 H2CO3,但我想尽可能简单地回答这个问题。 ;)
    【解决方案2】:

    在 Xcode 4.4 中,默认情况下会合成属性。因此,通过省略自己的综合,编译器会为您完成!

    See Apple docs - 特别是“编译器默认为未实现的@properties 自动调用@synthesize。”

    【讨论】:

    • 非常感谢!这种“异常”的 xcode 行为让我很困惑,因为“Objective-C 编程语言”文档中没有更新这个新功能。
    猜你喜欢
    • 2011-11-21
    • 2017-04-11
    • 2012-02-03
    • 2018-09-03
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    相关资源
    最近更新 更多