2

我遇到过 Objective-C 代码,它在 .m 文件中的 @implementation 行下方声明了一个变量,而不是在 .h 文件的 @interface 块中。然后它继续像私有 ivar 一样使用它。我无法找到有关以这种方式声明变量的文档,并且想知道影响。

例子:

。H

@interface MyClass {
    @private
    int _myPrivInt1;
}
@end

.m

@implementation
int _myPrivInt2;
@end

问题:

这两个变量之间的技术区别是什么?

是否与使用 @private 修饰符在 .h @interface 块中声明 ivar 相同,还是更像 C 全局变量?

以这种方式声明变量时是否有任何影响?

应该避免吗?

是否有一个术语可以声明像 _myPrivInt2 这样的变量,这会使我的谷歌搜索更加成功?

4

1 回答 1

3

您必须在接口块中声明实例变量。

@implementation
int _myPrivInt2;
@end

以这种方式声明变量,您实际上并没有为您的类声明 iVar。_myPrivInt2 将是一个全局变量,可以使用 extern 声明从代码的任何部分访问:

// SomeOtherFile.m
extern int _myPrivInt2;
...
_myPrivInt2 = 1000;

您可以检查 - 在 SomeOtherFile.m 中的代码执行后,您的 _myPrivInt2 变量将等于 1000。

您还可以为您的 _myPrivInt2 指定静态链接说明符,以便只能在当前翻译单元内访问它

@implementation
static int _myPrivInt2; // It cannot be accessed in other files now
@end
于 2010-09-16T13:36:06.773 回答