View Full Version : Two objects which reference each other...
Aquis
May 19, 2008, 05:22 AM
Okay, say I have the Obj-C classes, ObjectA and ObjectB. Until now, if I want ObjectA to "use" ObjectB, I include the line:
#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:
#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
May 19, 2008, 05:29 AM
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
May 19, 2008, 06:20 AM
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:
@class ObjectB;
By the way, is there a reason why you're using #include rather than #import?
yeroen
May 19, 2008, 08:02 AM
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
May 19, 2008, 08:07 AM
I would imagine that using #import rather than #include is the first step to solving whatever your problems are.
cmaier
May 19, 2008, 11:55 AM
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
May 20, 2008, 05:17 PM
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:
#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!
vBulletin® v3.8.6, Copyright ©2000-2012, Jelsoft Enterprises Ltd.