我有针对iPhone的情境编程。我有一个Object(对象A),它包含另一个Object(对象B)。有没有办法从对象B引用对象A?如果是这样,我该怎么做?
答案 0 :(得分:3)
没有。对象B需要有自己的指向对象A的指针。
答案 1 :(得分:2)
您可以让这些类互相引用,如下所示:
<强> 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