18

I'm making a Cocos2d game for iphone, and I have my main game mode, Game, which inherits from CCLayer.

I'm trying to make another game mode, MathGame, which inherits from Game, but when I try to compile, I get this error in MathGame.h:

Attempting to use the forward class 'Game' as superclass of 'MathGame'

I get the error even if the implementation and interface of MathGame are empty. And it only happens if I try to include MathGame.h in another file.

Here's the code for the Game class:

// Game.h
#import "cocos2d.h"
#import <GameKit/GameKit.h>
#import "SplashScreenLayer.h"

@interface Game : CCLayer
    // A bunch of stuff
@end

The new game type:

// MathGame.h
#import "Game.h"

@interface MathGame : Game
@end

And the main menu that includes both:

// SplashScreen.h
#import "cocos2d.h"
#import "Game.h"
#import "MathGame.h"
#import "HowToPlayLayer.h"
#import "AboutLayer.h"

@interface SplashScreenLayer : CCLayer
    // A bunch of stuff
@end

I can't find anything helpful online. Any ideas?

Mazyod
  • 22,319
  • 10
  • 92
  • 157
cstack
  • 2,152
  • 6
  • 28
  • 47

2 Answers2

34

You simply have an import cycle:

  1. Game imports SplashScreenLayer
  2. SplashScreenLayer imports MathGame
  3. MathGame imports Game

Your solution:

Leave the import inside the MathGame, and change the other imports to @class.

To sum it up:

// Game.h
#import "cocos2d.h"
#import <GameKit/GameKit.h>

@class SplashScreenLayer;
@interface Game : CCLayer
    // A bunch of stuff
@end

The new game type:

// MathGame.h
#import "Game.h"

@interface MathGame : Game
@end

And the main menu that includes both:

// SplashScreen.h
#import "cocos2d.h"
#import "HowToPlayLayer.h"
#import "AboutLayer.h"

@class Game;
@class MathGame;
@interface SplashScreenLayer : CCLayer
    // A bunch of stuff
@end

With your question answered above, let me explain a few things I already know from reading about forward declerations and import cycles:

First, go read about them! They are a very important part of Objective-C, and you don't want to miss it!

Secondly, use @class whenever you need that class for private variables or method parameters. Use imports for inheritance and strong properties.

Thirdly, don't forget to #import your forwarded classes in the implementation file!

Mazyod
  • 22,319
  • 10
  • 92
  • 157
  • HI. Regarding Thirdly, don't forget to #import your forwarded classes in the implementation file! - do you mean that in the .m files I have to import all the classes that I defined as @class ? why? – Dejell Feb 21 '13 at 07:35
  • @Odelya Because using @ class only notifies your class that there is a class that exists with that name, but it doesn't expose the methods and properties it has – Mazyod Feb 21 '13 at 08:29
  • well explained. i missed hat. – khunshan Jan 18 '16 at 12:52
1

In my case,I user the xx class and use the @class but not #import the .h file.and the compile complain..

frank
  • 2,327
  • 1
  • 18
  • 20