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

2019-02-25 11:48发布

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.

3条回答
Fickle 薄情
2楼-- · 2019-02-25 12:07

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

查看更多
孤傲高冷的网名
3楼-- · 2019-02-25 12:16

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

查看更多
Root(大扎)
4楼-- · 2019-02-25 12:19

In the header, use forward declaration:

@class IRCConnection;

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

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

查看更多
登录 后发表回答