Object reference
I have a situation programming for the iPhone. I have an Object (object A) that contains another Object (obj开发者_如何转开发ect B). Is there a way to reference object A from Object B? If so, how would I do it?
No. Object B needs to have its own pointer to Object 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
精彩评论