views:

303

answers:

3

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!

+5  A: 

Use @class A; and @class B; instead of #imports to tell the compiler to not worry about class definition, and just keep going because it will come across them later.

Basically, replace #import "A.h" with @class A;.

freespace
+10  A: 
e.James
+5  A: 

What you need to do is to "forward declare" your classes instead of importing the full definition. For example:

#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.

Martin Cote