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

Aquis

macrumors member
Original poster
Aug 7, 2007
63
0
Staffordshire, UK
Okay, say I have the Obj-C classes, ObjectA and ObjectB. Until now, if I want ObjectA to "use" ObjectB, I include the line:
Code:
#include <ObjectB.h>
...in ObjectA.h. But when I also want ObjectB to use ObjectA, and I try to do it the other way round at the same time, by having the line:
Code:
#include <ObjectA.h>
...in ObjectB.h, I get compile errors. So, basically, how do I allow ObjectA and ObjectB use each other?

Thanks,
Aquis
 

hhas

macrumors regular
Oct 15, 2007
126
0
You don't say what compile errors you're getting, but I'm guessing you need to forward declare some classes using the @class directive.
 

Nutter

macrumors 6502
Mar 31, 2005
432
0
London, England
Yes, in general it's best to use @class to forward-declare dependencies in your header files wherever possible, and import the files you need in the .m implementation file.

So, in ObjectA.h, you'd declare the following:

Code:
@class ObjectB;

By the way, is there a reason why you're using #include rather than #import?
 

yeroen

macrumors 6502a
Mar 8, 2007
944
2
Cambridge, MA
Are you actually using the classes themselves or pointers or references to the classes? In the latter case, you don't need to include the header files, just a forward declaration.
 

Sbrocket

macrumors 65816
Jun 3, 2007
1,250
0
/dev/null
I would imagine that using #import rather than #include is the first step to solving whatever your problems are.
 

cmaier

Suspended
Jul 25, 2007
25,405
33,474
California
I would imagine that using #import rather than #include is the first step to solving whatever your problems are.

ditto.

With #include, you end up having to wrap headers in #ifndef __FOO, #define _FOO to prevent multiply including them.
 

Aquis

macrumors member
Original poster
Aug 7, 2007
63
0
Staffordshire, UK
Thanks for the replies...

There's no particular reason that I'm using #include over #import, except that it's what is used to include Cocoa, and seems to mostly work. I've never seen the class directive before, I'll have a go at using it - in the meantime, thanks again!

Edit: Sorry, I am using #import actually...from the start, not sure why I put #include in the first message...
Edit: Also, the compiler reports that there is a syntax error before 'ClassA' in ClassB.h. ClassB.h is like this:
Code:
#import <Cocoa/Cocoa.h>

#import <ClassA.h>


@interface ClassB : NSObject {
	ClassA * myAInstance;
}

@end
Final Edit: Adding the @class directive does appear to work! Thanks for help!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.