I have two classes ClassA and Class B (they are viewControllers).
Class A is a delegate of classB.
ClassA “laucnhes” and instance of ClassB.
ClassB call methods on classA.
Let’s say it’s :
#import "ClassB.h"
@interface ClassA : NSObject {
ClassB* subController;
}
- (void) doThis;
-------------------------------
#import "ClassA.h"
@interface ClassB : NSObject {
ClassA* delegate;
}
-------------------------------
@implementation ClassB
- (void) someMethod {
AnObject* myObj = [self.delegate.arr objectAtIndex:8];
[self.delegate doThis];
}
Doing that way, A must import B, and B must import A.
If B do not import A (with just @class A), there is a compile error for the used attribute from A.
If B imports A, there is a compile error on the ClassA* delegateline.
Why do I have those compile errors? Doesn’t #import protect again recursive calls ?
I don’t need a solution to solve that problem, I know how I may do this.
But I wonder why my #import cause those problems. These are not #includes…
#importprotects against repeatedly importing the same header into the same module, whether by circular includes/imports or not. It protects against that by not letting you do it: Only the first#importof a header works; subsequent#imports of the same header are ignored.In a circular
#includesituation, the preprocessor would go around the circle some number of times and then fail the build before you even get to compilation. Using#importprevents the preprocessor from getting wedged and lets the preprocessor succeed, but circular-#importcode is still dodgy at best and usually will not compile.So, on to your specific situation.
For the code you showed in your question,
@classwill work in either or both headers, and indeed you should use it in both. You’ll also need to#importboth headers in both .m files.If you mean “there is a compile error at each point where I use that attribute of type
ClassA *”, then yes: You can’t talk to that object because you haven’t imported its interface, so the compiler doesn’t know what messages you can send to aClassAinstance. That’s why you need to import its interface.If both headers import each other, then you have this:
There is no way this can work without one interface preceding the other without the other interface preceding it. That’s the circle you’re running into—the circle that
#importexists to break.#includeallows the circle, and thereby gets wedged:Hence
#import.So you cannot import each header from the other. Hence
@class.But you still need to import each header from each module. That is, in fact, exactly what you need to do: Use
@classin each header and use#import(on both headers) in each module.