代码之家  ›  专栏  ›  技术社区  ›  Sebastien Martin

未申报的IVAR?

  •  2
  • Sebastien Martin  · 技术社区  · 16 年前

    例子:

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

    上午

    @implementation
    int _myPrivInt2;
    @end
    

    问题:

    这两个变量在技术上有什么区别?

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

    应该避免吗?

    有没有一个术语可以用来声明变量,比如myPrivInt2,这会让我的google搜索更加成功?

    1 回复  |  直到 16 年前
        1
  •  3
  •   Vladimir    16 年前

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

    @implementation
    int _myPrivInt2;
    @end
    

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

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

    您还可以将静态链接说明符指定给您的\u myPrivInt2,这样就只能在当前翻译单元中访问它

    @implementation
    static int _myPrivInt2; // It cannot be accessed in other files now
    @end