Matthijn
Matthijn

Reputation: 3234

#import in objective C: Am I doing this wrong?

Sorry, couldn't find a more appropriate title.

In My code I have two classes which should know of each others existence. So I use an instance variable which points to the other class. For that to work (I guess?) the other classes headers file should be imported so it knows which methods it has and such.

Here is my code (stripped down)

MainMenuController.h:

    #import <Cocoa/Cocoa.h>
    #import "IRCConnection.h"

    @interface MainMenuController : NSViewController {    
        IRCConnection *ircConnection;
    }

    @property (strong) IRCConnection *ircConnection;

    @end

IRCConnection.h:

    #import <Foundation/Foundation.h>
    #import "MainMenuController.h"

    @interface IRCConnection : NSObject {

        MainMenuController *mainMenuController;
    }

    @property (strong) MainMenuController *mainMenuController;

    @end

As you can see they both import each other, but this creates an error (Unknown type name 'IRCConnection') in one, and in the other Unknown type name 'MainMenuController'.

However when the connection is just one way (e.g. only MainMenuController knows about IRCConnection) and thus there is only an import statement in one of the two, it works fine.

How can I have them to know about each other? In both ways.

Hope this question makes any sense.

Upvotes: 3

Views: 2176

Answers (3)

hamstergene
hamstergene

Reputation: 24429

In the header, use forward declaration:

@class IRCConnection;

@interface MainMenuController : NSViewController {    
    IRCConnection *ircConnection; // ok
}

In the source file (.m), do #import.

Upvotes: 3

Thilo
Thilo

Reputation: 262474

You cannot have circular imports. You need to break them up, or introduce some forward declarations.

Upvotes: 0

Matthias Bauch
Matthias Bauch

Reputation: 90117

you could remove the import from IRCConnection.h and use a @class statement instead.

like this:

#import <Foundation/Foundation.h>

@class MainMenuController;

@interface IRCConnection : NSObject {

then add a #import "MainMenuController.h" to IRCConnection.m

Upvotes: 7

Related Questions