对象参考

时间:2009-11-17 23:46:03

标签: iphone objective-c oop

我有针对iPhone的情境编程。我有一个Object(对象A),它包含另一个Object(对象B)。有没有办法从对象B引用对象A?如果是这样,我该怎么做?

2 个答案:

答案 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