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

2019-02-25 12:09发布

问题:

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.

回答1:

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



回答2:

In the header, use forward declaration:

@class IRCConnection;

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

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



回答3:

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