OStack程序员社区-中国程序员成长平台

标题: ios - 为什么我必须在头文件中定义两次变量? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 17:20
标题: ios - 为什么我必须在头文件中定义两次变量?

为什么我必须在头文件中定义两次变量?这些变量之间有什么区别?

第一个定义在这里:

@interface MyController: UIViewController
{
    NSInteger selectedIndex;
}

第二个定义在这里:

@property (nonatomic) NSInteger selectedIndex;



Best Answer-推荐答案


What you're seeing was required in earlier versions of Objective-C, but isn't any more.

In the first versions of Objective-C used by NeXT up until the new runtime was introduced (with Objective-C 2.0 on Mac OS X), all instance variables had to be declared as part of the class's structure in its @interface. The reason was that if you subclassed a class, the compiler needed to know the instance variable layout of the class so it could see at what offset to put the subclass's instance variables.

When properties were introduced, synthesized properties had to be "backed" by an instance variable in the class's structure. Therefore you had to declare both an instance variable and the property.

All of the above is no longer true. Newer Objective-C is less fragile in the way it looks up instance variable offsets, which has meant a few changes:

So, to reiterate, you only needed to declare both the instance variable and a synthesized property in older versions of the Objective-C language. What you're seeing is redundant and should not be considered a "best practice".

[Source]

关于ios - 为什么我必须在头文件中定义两次变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39116583/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4