views:

36

answers:

2

Let’s say you wish to have two classes like so, each declaring an instance variable that is of the other’s class.

@interface A : NSObject {
    B   *something;
}
@end

@interface B : NSObject {
    A   *something;
}
@end

It seems to be impossible to declare these classes with these instance variables. In order for A to include an IV of class B, B must already be compiled, and so its @interface must come before A’s. But A’s must be put before B’s for the same reason.

Putting the two class declarations in separate files, and #import-ing each other’s ‘.h’s doesn’t work either, for obvious reasons.

So, what is the solution? Or is this either (1) impossible or (2) indicative of a bad design anyway?

+3  A: 

This is what the @class keyword is for. It tells the compiler that something is used as a class without the compiler necessarily knowing anything about it.

@class B;    
@interface A : NSObject {
    B   *something;
}
@end

@class A;
@interface B : NSObject {
    A   *something;
}
@end
jshier
+5  A: 

To do that you need to use forward class declaration:

//a.h
@class B;

@interface A : NSObject {
    B   *something;
}
@end

// b.h

@class A

@interface B : NSObject {
    A   *something;
}
@end

So compiler will know that A and B are classes. And in implementation files for both classes just include a.h and b.h headers.

Vladimir