PDA

View Full Version : Circular inclusion ... needed?




ryanknu
Sep 12, 2008, 04:43 PM
Hey everyone,
I got this really confusing (for me, at least) issue where I have two Obj-C classes that need to use each other. Here's some examples

// file AObj.h
#import <Cocoa/Cocoa.h>
#import "BObj.h"

@interface AObj : NSObject {
BObj *b;
}

-(void) setBObj:(BObj *) b; // HERE

and file:

// file BObj.h
#import <Cocoa/Cocoa.h>
#import "AObj.h"

@interface BObj : NSObject {
AObj *a;
}

Both of them require importing the header file of the other object, but Obj-C won't let me do this, and at line "HERE" I get the error "syntax error before 'BObj'."

If someone could enlighten me on how to import both headers without getting stuck importing in a circle, that would be useful. I also tried putting the BObj into the global scope, but I guess I don't know how to do that. Any help would be helpful!



kainjow
Sep 12, 2008, 04:49 PM
Use @class:

// file AObj.h
#import <Cocoa/Cocoa.h>
@class BObj;

@interface AObj : NSObject {
BObj *b;
}

-(void) setBObj:(BObj *) b;

Then #import "BObj.h" in the .m file. @class just basically tells the compiler that you have a class BObj but you don't need to know anything else about it at this time. But in the implementation file you will need to #import it because then you will use methods on the object.

The only time you should use #import/#include in your .h file is if you're subclassing or referencing a data type not part of Cocoa or standard C.

ryanknu
Sep 12, 2008, 04:51 PM
Thanks! I noticed I could include the header from the other implementation file, but that never really helped me add the other class as a field...