How can I solve this problem with bidirectional dependencies in Objective-C classes?

Well, this can be a very stupid beginner question, but:

I have a ClassA that will create a child of the ClassB class and assign it to an instance variable. Details: ClassA will allocate and initialize ClassB in the designated initializer and assign it to the childObject instance variable. The title is as follows:

#import <Foundation/Foundation.h>
#import "ClassB.h"

@interface ClassA : NSObject {
    ClassB *childObject;
}

@end

Then there is a ClassB header. ClassB must have a reference to ClassA.

#import <Foundation/Foundation.h>
#import "ClassA.h"

@interface ClassB : NSObject {
    ClassA *parentObject;
}

- (id)initWithClassA:(ClassA*)newParentObject;

@end

When a ClassA object creates a child of class B, the ClassA will call the assigned initializer of the ClassB, where it must go through (self).

, - , , . , , . . : "error: " ClassA ". ClassA, ClassA * parentObject ( ClassA), .

, ( ): UIScrollView. . , "" - UIScrollView. UIScrollView - . - , UIScrollView, . , , , "" , .

!

+4
3

. @class , #import .m:

// ClassA.h:
@class ClassB;
@interface ClassA : NSObject
{
    ClassB *childObject;
}
@end


// ClassA.m:
#import "ClassA.h"
#import "ClassB.h"
@implementation ClassA
//..
@end


// ClassB.h
@class ClassA;
@interface ClassB : NSObject
{
    ClassA *parentObject;
}
- (id)initWithClassA:(ClassA*)newParentObject;
@end


// ClassB.m:
#import "ClassB.h"
#import "ClassA.h"
@implementation ClassB
//..
@end
+15

@class A; @class B; #import, , , , .

#import "A.h" @class A;.

+5

, " " . :

#import <Foundation/Foundation.h>

@class ClassB; // Tell the compiler that ClassB exists

@interface ClassA : NSObject {
    ClassB *childObject;
}

@end

And you do something similar for the ClassB header file.

+5
source

All Articles