在obj-c中可以获取属性的父实例吗?

时间:2009-01-12 19:09:39

标签: objective-c runtime

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

@interface AObject : NSObject {
}

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

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

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

不,超级是为了上课。

我问的是如何获取父对象(就像在树中一样)。

但我认为这是不可能的......并且是孩子与父母的关系。

答案 3 :(得分:0)

您必须让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;
}

答案 4 :(得分:0)

如果你真的想这样做,你可以覆盖AObject中的“retain”方法来查看当前堆栈并查找调用类的ID。对不起,你必须调查如何做到这一点,我只知道你可以从其他研究中获得。

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

相关问题