Circular inclusion ... needed?

Discussion in 'Mac Programming' started by ryanknu, Sep 12, 2008.

  1. macrumors newbie

    Joined:
    Sep 12, 2008
    #1
    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!
     
  2. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    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.
     
  3. thread starter macrumors newbie

    Joined:
    Sep 12, 2008
    #3
    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...
     

Share This Page