@interface或@implementation中的私有ivar [英] Private ivar in @interface or @implementation
问题描述
是否有任何理由在@interface
而不是@implementation
中声明私有ivar?
Is there any reason to declare a private ivar in @interface
instead of @implementation
?
我在互联网上看到这样的代码(包括苹果):
I see code like this all over the internet (including documentation provided by Apple):
Foo.h
@interface Foo : NSObject {
@private
id _foo;
}
@end
Foo.m
@implementation Foo
// do something with _foo
@end
头文件定义了一个类的公共接口,而一个私有的ivar是...好...私有的.那么为什么不这样声明呢?
The header file defines the public interface of a class, whereas a private ivar is... well... private. So why not declare it like this?
Foo.h
@interface Foo : NSObject
@end
Foo.m
@implementation Foo {
@private
id _foo;
}
// do something with _foo
@end
推荐答案
在@implementation
中声明实例变量是Obj-C的最新功能,这就是为什么您在@interface
中看到很多带有它们的代码的原因-别无选择.
Declaring instance variables in the @implementation
is a recent feature of Obj-C, this is why you see a lot of code with them in the @interface
- there was no other choice.
如果您使用的编译器支持在实现中声明实例变量,则声明它们可能是最好的默认值-仅在需要其他人访问它们时才将它们放在接口中.
If you are using a compiler which supports declaring instance variables in the implementation declaring them there is probably the best default - only put them in the interface if they need to be accessed by others.
修改:其他信息
实例变量是隐式隐藏的(实际上是私有的),并且可见性 无法更改-@public
,@protected
和@private
不产生编译器错误(至少使用当前的Clang),但会被忽略.
Instance variables declared in the implementation are implicitly hidden (effectively private) and the visibility cannot be changed - @public
, @protected
and @private
do not produce compiler errors (with the current Clang at least) but are ignored.
这篇关于@interface或@implementation中的私有ivar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!