I\'m working on a game for iPad using cocos2d which involves a board filled with different types of tiles. I\'ve created a custom class called Tile
as a general
This may not be the problem, but what happens if you remove the "#import "Board.h"" from the Tile.h file. You might have a problem with circular referencing
Two files cannot import each other. You need to move the import directives to the implementation files, and instead just forward-declare the classes in the headers (e.g. @class Tile;
in Board.h).
The reason circular imports don't work is because #import
literally includes the text from the imported file in-place. But it also ensures that the text from a file will only be included once, in order to avoid duplicate declarations. So when Tile.h says that the text from Board.h needs to go before it, and Board.h says the text from Tile.h needs to go before it, there's literally nothing the compiler can do — one of them needs to go first, and that file is going to complain because it was expecting the other one to already be there.
This is a classic problem with headers importing headers. You have a circle here: Tile.h is importing Board.h, which imports Tile.h. This confuses the compiler -- it gets stuck in a loop.
You solve this by not importing headers into headers. You still need to let the compiler know about Tile
, however. In Board.h, make a "forward declaration" of the class:
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@class Tile; // Dear compiler,
// Tile is a class that I will need to refer
// to in this file. Please consider it to be a
// type; I promise it'll be defined at runtime.
// Sincerely, stephenalexbrowne
@interface Board : NSObject
//etc.
This assures the compiler that there is a class called Tile
that will exist at runtime; you can then refer to that name in the remainder of your header. In your implementation for Board
, you import Tile.h. That will let the compiler see the methods and properties associated with the Tile
class where they are needed.
Likewise, move the #import "Board.h"
into Tile.m. Since you aren't referring to the Board
class in Tile.h, you don't need to make a forward declaration.
In general, it is best to import your class headers only into the implementation files where they are needed. Framework headers, since they will never cause a cycle with your code, can and -- because you need to refer to many of the classes declared in them -- should be imported into your headers.