Objective-c – How to solve this Problem with bidirectional dependencies in Objective-C classes

cocoacocoa-touchiphoneobjective cuikit

Okay, this might be a very silly beginner question, but:

I've got an ClassA, which will create an child object from ClassB and assign that to an instance variable. In detail: ClassA will alloc and init ClassB in the designated initializer, and assign that to the childObject instance variable. It's header looks like this:

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

@interface ClassA : NSObject {
    ClassB *childObject;
}

@end

Then, there is the header of ClassB. ClassB has to have a reference to ClassA.

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

@interface ClassB : NSObject {
    ClassA *parentObject;
}

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

@end

When the ClassA object creates an child object from ClassB, then the ClassA object will call the designated initializer of the ClassB object, where it has to pass itself (self).

I feel that there is something wrong, but for now I don't get exactly what it is. One think I know is that this does not work. They can't bove import eachother. The compiler just tells me: "error: syntax error before 'ClassA'". When I remove the import statement for importing ClassA, remove the ClassA *parentObject instance variable and remove the designates initializer (that takes ClassA reference), then it works.

Now, here is what I want to achieve (if this matters): I need some very special and complex behavior in an UIScrollView. So I decided to subclass it. Because the main part is going to be done inside the delegate methods, I decided to create an "generic" delegate object for my subclass of UIScrollView. My UIScrollView subclass then creates automatically that special delegate object and assigns it to its delegate property. The delegate object itself needs a reference to it's parent, the customized UIScrollView, so that it has access to the subviews of that scroll view. But anyways, even if there's a better way to get this problem done, I'd still like to know how I could do it that way with two "interdependent" objects that need eachother.

Any suggestions are welcome!

Best Answer

You don't need to import those classes in the header files. Use @class in the header files, and then use #import only in the .m files:

// 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
Related Topic