views:

73

answers:

2

I have a situation programming for the iPhone. I have an Object (object A) that contains another Object (object B). Is there a way to reference object A from Object B? If so, how would I do it?

+3  A: 

No. Object B needs to have its own pointer to Object A.

Dave DeLong
+2  A: 

You can have the classes reference each other like this:

ClassA.h:

@class ClassB // let the compiler know that there is a class named "ClassB"

@interface ClassA : NSObject {
    ClassB *objectB;
}

@property (nonatomic, retain) ClassB *objectB;

@end

ClassB.h:

@class ClassA; // let the compiler know that there is a class named "ClassA"

@interface ClassB : NSObject {
    ClassA *objectA;
}

@property (nonatomic, assign) ClassA *objectA; // "child" object should not retain its "parent"

@end

ClassA.m:

#import "ClassA.h"
#import "ClassB.h"

@implementation ClassA

@synthesize objectB;

- (id)init {
    if (self = [super init]) {
     objectB = [[ClassB alloc] init];
     objectB.objectA = self;
    }

    return self;
}

@end

ClassB.m:

#import "ClassA.h"
#import "ClassB.h"

@implementation ClassB;

@synthesize objectA;

- (id)init {
    if (self = [super init]) {
     // no need to set objectA here
    }

    return self;
}

@end
gerry3
That worked - thank you. One issue is that the line @class directive should have a semicolon, such as `@class ClassA;`
Chris
Fixed @class declarations.
gerry3
+1, except I would make B's A property `assign` and not `retain`, just to avoid a retain cycle.
Dave DeLong
Changed objectA property (in ClassB) to "assign".
gerry3