views:

150

answers:

6

I wonder if is possible in obj-c to acces the parent instance from a property, like:

@interface AObject : NSObject {
}

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

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

I'm not entirely sure what you're asking. Are you looking for the super keyword?

Marc Charbonneau
+1  A: 

Not that I'm aware of. You would have to make AObject aware of it's parent. There may be other ways to do it if you fiddle with the runtime, but it's just easier to make AObject require a parent.

Martin Pilkington
A: 

No, the super is for get the class.

I'm asking is in how get the parent object (like in a tree).

But I think that is not possible... and is necesary associate the child with the parent.

mamcx
A: 

You would have to make AObject aware of DbObject, but also you should access the properties of DbObject using selectors.

@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;
}
dreamlax
A: 

Ok, that is fair.

mamcx
A: 

If you really want to do this, you could override the "retain" method in AObject to look at the current stack and look for the ID of the calling class. Sorry, you'll have to investigate how to do that, I just know you can from other research.

If what you are really trying to do is have some kind of debug statement that tells you who owns a particular object - you can just override retain and set breakpoints or put helpful data dumps in there.

Kendall Helmstetter Gelner