@interface中的实例变量;标题与实现

时间:2023-01-21 15:05:03

Is there any difference between declaring a private instance variable in the header vs declaring it in the implementation?

在标头中声明私有实例变量与在实现中声明它之间有什么区别吗?

in TestObj.h

在TestObj.h中

@interface TestObj : NSObject
{
    int test;
}
@end

vs in TestObj.m

在TestObj.m中的vs

@interface TestObj()
{
    int test;
}
@end

Both seem equivalent to me, is there any actual difference between declaring an instance variable in the header vs in the implementation, if not which is preferred? The @interface within the implementation file just seems like a way to declare private properties, does it have any other purpose outside that?

两者似乎都等同于我,在标题和实现中声明实例变量之间是否存在任何实际差异,如果不是首选的话?实现文件中的@interface似乎是一种声明私有属性的方式,它之外还有其他任何用途吗?

2 个解决方案

#1


15  

The preference is generally to place private instance variables and properties in the private class extension (in the .m) and leave the public interface file (.h) for those properties and methods that are truly part of the public interface.

首选项通常是将私有实例变量和属性放在私有类扩展中(在.m中),并将公共接口文件(.h)保留为真正属于公共接口的属性和方法。

It helps isolate implementation details from the public interface and makes everything much cleaner. It also ensures that external classes do not inadvertently alter the private variables of this class.

它有助于将实现细节与公共界面隔离开来,使一切更加清晰。它还确保外部类不会无意中更改此类的私有变量。

See Class Extensions Extend the Internal Implementation.

请参阅类扩展扩展内部实现。

#2


7  

Greg Parker's comment on the accepted answer is the best answer here:

Greg Parker对接受的答案的评论是最好的答案:

There is one functional difference: ivars in the class's @interface are @protected by default, and ivars in a class extension @interface or in @implementation are @private by default.

有一个功能区别:默认情况下,类的@interface中的ivars是@protected,默认情况下类扩展名@interface或@implementation中的ivars是@private。

#1


15  

The preference is generally to place private instance variables and properties in the private class extension (in the .m) and leave the public interface file (.h) for those properties and methods that are truly part of the public interface.

首选项通常是将私有实例变量和属性放在私有类扩展中(在.m中),并将公共接口文件(.h)保留为真正属于公共接口的属性和方法。

It helps isolate implementation details from the public interface and makes everything much cleaner. It also ensures that external classes do not inadvertently alter the private variables of this class.

它有助于将实现细节与公共界面隔离开来,使一切更加清晰。它还确保外部类不会无意中更改此类的私有变量。

See Class Extensions Extend the Internal Implementation.

请参阅类扩展扩展内部实现。

#2


7  

Greg Parker's comment on the accepted answer is the best answer here:

Greg Parker对接受的答案的评论是最好的答案:

There is one functional difference: ivars in the class's @interface are @protected by default, and ivars in a class extension @interface or in @implementation are @private by default.

有一个功能区别:默认情况下,类的@interface中的ivars是@protected,默认情况下类扩展名@interface或@implementation中的ivars是@private。