代码之家  ›  专栏  ›  技术社区  ›  Richard J. Ross III

多权限Objective-C变量

  •  0
  • Richard J. Ross III  · 技术社区  · 15 年前

    我有一个类似的数据模型:

                                              (in another project)
     ________________________________        _______________________
    |                                |      |                       |
    |  Graph                         |      | DetailedGraph         |
    |  GraphListener lstnr           |      | (needs to access foo) |
    |  NSString foo                  | <----|_______________________|     
    |  ____________________________  | 
    | | GraphListener              | |       _______________________
    | | Graph enclosing            | |      |                       |
    | | (also needs to access foo) | |      | OtherClass            |
    | |____________________________| |      | (cannot access foo)   | 
    |________________________________|      |_______________________|
    

    @interface Graph_Listener
    {
         @private
         Graph *enclosing;
    }
    @end
    
    @interface Graph
    {
        @package
        NSString *foo;
    } 
    @end
    

    现在,我的问题是,当我开始子类化 Graph ,并使 DetailedGraph 类,它在另一个项目中,仍需要访问 foo GraphListener 细节图

    1 回复  |  直到 15 年前
        1
  •  1
  •   bbum    15 年前

    首先,我希望您的两个类继承自NSObject,而不是根类。在iOS上创建Objective-C的新根实际上相当困难,除非您将实例与Foundation/UIKit完全隔离。

    两种可能的解决方案:

    • 不要直接进入iVar。创建和使用访问器,可能是通过 @property

    • 宣布ivar是“公开的”然后骗走。脆弱的,非典型的,充满危险的。


    Objective-C中的Private实际上是指“那边的编译单元在这里看不到这个声明”。

    因此,如果需要,您可以声明一个属性(比如说)为public readonly和private readwrite:

    食物:

    @interface Foo....
    @property(readonly) int x;
    @end
    

    @interface Foo()
    @property(readwrite) int x;
    @end
    

    食品: #导入“Foo+Private.h” @实现Foo @合成x; @结束

    任何导入Foo.h的文件都只能看到x是只读的。Foo的实现将看到它是readwrite。其他任何导入Foo+Private.h的东西也会这样。