我遇到过 Objective-C 代码,它在 .m 文件中的 @implementation 行正下方声明一个变量,而不是在 .h 文件的 @interface block 中。然后它像私有(private) ivar 一样使用它。我无法找到有关以这种方式声明变量的文档,并且想知道其影响。
示例:
.h
@interface MyClass {
@private
int _myPrivInt1;
}
@end
.m
@implementation
int _myPrivInt2;
@end
问题:
这两个变量之间有什么技术差异?
这与使用 @private 修饰符在 .h @interface block 中声明 ivar 相同还是更像 C 全局变量?
以这种方式声明变量有什么影响吗?
应该避免吗?
是否有一个术语来声明像 _myPrivInt2 这样的变量,这会让我的谷歌搜索更加成功?
最佳答案
您必须在接口(interface) block 中声明实例变量。
@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
关于objective-c - 未声明的伊瓦尔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3727106/