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?
+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
2009-11-18 00:01:44
That worked - thank you. One issue is that the line @class directive should have a semicolon, such as `@class ClassA;`
Chris
2009-11-18 04:12:41
Fixed @class declarations.
gerry3
2009-11-18 06:16:48
+1, except I would make B's A property `assign` and not `retain`, just to avoid a retain cycle.
Dave DeLong
2009-11-18 06:23:19
Changed objectA property (in ClassB) to "assign".
gerry3
2009-11-18 09:17:06