且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么必须在Header文件中定义变量两次?

更新时间:2023-02-05 20:05:38




在Objective-C的早期版本中需要
,但是没有更多。引入了新的
运行时(在Mac OS X上使用Objective-C 2.0),所有的
实例变量都必须声明为类结构的一部分
在其 @interface 。原因是如果你子类化一个类
,编译器需要知道类
的实例变量布局,所以它可以看到以什么偏移量放置子类的实例
变量。 p>

引入属性时,合成属性必须由类结构中的实例变量
支持。因此
你必须声明一个实例变量和属性。



上面所有的都不是真的。较新的Objective-C在它查找实例变量偏移的方式上不太脆弱,这意味着
几个变化:




  • 并非所有实例变量都需要在 @interface 中。现在可以在 @implementation 中定义:虽然不在类别中,但
    可能会出现冲突和其他问题。


  • 您可以通过编程方式将实例变量添加到您在运行时创建的类中(只有在您注册之前)才能推断和创建合成属性的实例变量。该类作为
    可用于系统)。



因此,要重申,您只需要声明实例
变量和旧版本的
Objective-C语言中的合成属性。您看到的是多余的,不应将
视为***做法。


[来源]


Why must I define variables twice in the header file? What differences are there between these variables?

The first definition is here:

@interface MyController: UIViewController
{
    NSInteger selectedIndex;
}

The second definition is here:

@property (nonatomic) NSInteger selectedIndex;

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:

  • not all instance variables need to be in the @interface. They can now be defined in the @implementation: though not in categories due to the possibilities of ***ing and other issues.
  • instance variables for synthesized properties can be inferred and created based on the property definition.
  • you can programmatically add instance variables to classes you're creating at runtime (only before you've registered the class as available to the system).

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]