Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

ryanknu

macrumors newbie
Original poster
Sep 12, 2008
12
0
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

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

@interface AObj : NSObject {
	BObj *b;
}

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

and file:

Code:
// 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

Moderator emeritus
Jun 15, 2000
7,958
7
Use @class:

Code:
// file AObj.h
#import <Cocoa/Cocoa.h>
[b][color=red]@class BObj;[/color][/b]

@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

macrumors newbie
Original poster
Sep 12, 2008
12
0
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...
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.