Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#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.

like image 479
Matthijn Avatar asked Mar 23 '26 09:03

Matthijn


2 Answers

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

like image 97
Matthias Bauch Avatar answered Mar 24 '26 21:03

Matthias Bauch


In the header, use forward declaration:

@class IRCConnection;

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

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

like image 26
hamstergene Avatar answered Mar 24 '26 22:03

hamstergene