Two objects which reference each other...

Discussion in 'Mac Programming' started by Aquis, May 19, 2008.

  1. Aquis macrumors member

    Joined:
    Aug 7, 2007
    Location:
    Staffordshire, UK
    #1
    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
     
  2. hhas macrumors regular

    Joined:
    Oct 15, 2007
    #2
    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.
     
  3. Nutter macrumors 6502

    Joined:
    Mar 31, 2005
    Location:
    London, England
    #3
    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?
     
  4. yeroen macrumors 6502a

    yeroen

    Joined:
    Mar 8, 2007
    Location:
    Cambridge, MA
    #4
    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.
     
  5. Sbrocket macrumors 65816

    Sbrocket

    Joined:
    Jun 3, 2007
    Location:
    /dev/null
    #5
    I would imagine that using #import rather than #include is the first step to solving whatever your problems are.
     
  6. cmaier macrumors G3

    Joined:
    Jul 25, 2007
    Location:
    California
    #6
    ditto.

    With #include, you end up having to wrap headers in #ifndef __FOO, #define _FOO to prevent multiply including them.
     
  7. Aquis thread starter macrumors member

    Joined:
    Aug 7, 2007
    Location:
    Staffordshire, UK
    #7
    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!
     

Share This Page