【问题标题】:In obj-c is possible to get the parent instance of a property?在 obj-c 中是否可以获取属性的父实例?
【发布时间】:2009-01-12 19:09:39
【问题描述】:

我想知道在 obj-c 中是否可以从属性访问父实例,例如:

@interface AObject : NSObject {
}

-(void) sample{
 NSLog("%@", [[self parentInstance] Id]);
}

@interface DbObject : NSObject {
    NSInteger Id;
    AObject* ob;
}

【问题讨论】:

    标签: objective-c runtime


    【解决方案1】:

    我不知道。您必须让 AObject 知道它的父级。如果您摆弄运行时,可能还有其他方法可以做到这一点,但让 AObject 需要父级更容易。

    【讨论】:

      【解决方案2】:

      您必须让AObject 知道DbObject,但您还应该使用选择器访问DbObject 的属性。

      @interface AObject : NSObject
      {
          id father;
      }
      - (id) initWithFather:(id) theFather;
      - (void) sample;
      @end
      
      
      @implementation AObject
      - (id) initWithFather:(id) theFather
      {
          father = theFather;
          return self;
      }    
      
      - (void) sample
      {
          NSLog (@"%d", [father Id]);
      }
      @end
      
      
      @interface DbObject : NSObject
      {
          NSInteger Id;
      }
      - (id) initWithId:(NSInteger) anId;
      - (NSInteger) Id;
      @end
      
      
      @implementation DbObject
      - (id) initWithId:(NSInteger) anId;
      {
          Id = anId;
          return self;
      }
      
      - (NSInteger) Id
      {
          return Id;
      }
      @end
      
      
      int main (int argc, char *argv[])
      {
          DbObject *myDbObject = [[DbObject alloc] initWithId:5];
          AObject *myAObject = [[AObject alloc] initWithFather:myDbObject];
      
          [AObject sample];
      
          return 0;
      }
      

      【讨论】:

        【解决方案3】:

        我不完全确定你在问什么。您在寻找super 关键字吗?

        【讨论】:

          【解决方案4】:

          不,super是用来获取类的。

          我要问的是如何获取父对象(比如在树中)。

          但我认为这是不可能的......并且有必要将孩子与父母联系起来。

          【讨论】:

            【解决方案5】:

            如果你真的想这样做,你可以重写 AObject 中的“retain”方法来查看当前堆栈并查找调用类的 ID。抱歉,您必须研究如何做到这一点,我只知道您可以通过其他研究。

            如果您真正想做的是使用某种调试语句告诉您谁拥有特定对象 - 您可以覆盖保留并设置断点或在其中放置有用的数据转储。

            【讨论】:

              猜你喜欢
              • 2020-07-14
              • 2013-05-22
              • 2016-05-17
              • 1970-01-01
              • 1970-01-01
              • 2020-01-09
              • 2023-04-04
              • 1970-01-01
              • 2018-02-05
              相关资源
              最近更新 更多