Objective c 是否需要在@interface中声明IVAR以匹配属性?

Objective c 是否需要在@interface中声明IVAR以匹配属性?,objective-c,interface,properties,instance-variables,Objective C,Interface,Properties,Instance Variables,可能重复: 我被这两段代码弄糊涂了: 第一: //.h @interface Student : NSObject { } @property (nonautomic, copy) NSString *name; @property (nonautomic, retain) NSNumber *age; @end //.m @implementation Student @synthesize name; @synthesize age; @end 第二:

可能重复:

我被这两段代码弄糊涂了:

第一:

//.h
@interface Student : NSObject {

}
    @property (nonautomic, copy) NSString *name;
    @property (nonautomic, retain) NSNumber *age;
@end

//.m
@implementation Student
    @synthesize name;
    @synthesize age;
@end
第二:

//.h
@interface Student : NSObject {
    NSString *name;   // <<============ difference
    NSNumber *age;    // <<============ difference
}
    @property (nonautomic, copy) NSString *name;
    @property (nonautomic, retain) NSNumber *age;
@end

//.m
@implementation Student
    @synthesize name;
    @synthesize age;
@end
/.h
@接口学生:NSObject{

NSString*name;//从现代运行时开始(x86_64和ARM6…以及iOS模拟器)您不再需要声明合成IVAR。在第一个示例中,@synthetic为您添加实例变量。

同意@Joshua。我一开始也对这一点感到困惑。在运行时更新之后,基本上是旧的约定vs新的约定。我想苹果意识到,当您需要eclare@property,那么为什么不让@synthesis在创建setter和getter时处理它呢。我们少写一条语句,耶

(我认为,在早期的WWDC视频中解释了其中一些惯例变化)

根据运行时,访问器合成的行为存在差异(另请参见“运行时差异”):

  • 对于旧版运行时,实例变量必须已经在当前类的@interface块中声明。如果存在与属性同名的实例变量,并且如果其类型与属性的类型兼容,则将使用该实例变量,否则将出现编译器错误

  • 对于现代运行时(请参阅《Objective-C运行时编程指南》中的“运行时版本和平台”),会根据需要合成实例变量。如果已经存在同名的实例变量,则会使用它


你的属性应该标记为
非原子的
,而不是
非自动的
@5StringRyan这个问题要求你理解运行时有多个版本,这是来自不同的知识水平。@Joshuawinberg-我不明白,他问“那么需要在{}中声明变量吗?”我提到的SO帖子的创建者说,“这仍然有效吗?”(指的是创建没有IVAR的属性)。此外,该帖子上被接受的答案与您的答案非常相似。哦,我理解并同意答案是相同的,但问题却大不相同:)