开发者

Object reference

开发者 https://www.devze.com 2022-12-12 06:29 出处:网络
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 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号