我正在使用cocos2d框架开发iPhone游戏,最近遇到了一个我似乎无法解决的问题。在向我的项目添加一个新类并在其中完成一些工作后,我尝试编译我的代码,但几个我什至没有接触过的类都崩溃了。看起来这些类只是忘记了如何导入外部类。我在我的几个类(class)中都遇到了错误,但这里有一个例子:
#import "cocos2d.h"
#import "XZombie.h"
#import "WayPoint.h"
#import "XBuilding.h"
//@class XBuilding;
@interface Hoarde : CCNode
{
float _spawnRate;
int _totalXombies;
NSMutableArray *_path;
XBuilding *_target;
NSMutableArray *_zombies;
bool _zombiesReset;
}
@property (nonatomic) float spawnRate;
@property (nonatomic) int totalXombies;
@property (nonatomic, retain) NSMutableArray *path;
@property (nonatomic, retain) XBuilding *target;
@property (nonatomic, retain) NSMutableArray *zombies;
@property (nonatomic, assign) bool zombiesReset;
- (id) initWithZombieCount:(int)totalXombies Target:(XBuilding *) target SpawnRate:(float)spawnrate;
- (void) resetZombies;
@end
我在读取 XBuilding *_target;
的行上收到错误
如果我取消注释 @class XBuilding;
,错误就会消失,因此虽然这并不能真正解决我的问题,但它为我提供了解决该问题的工具。
如果我对所有有问题的文件执行@class
技巧,我就可以解决这个问题。问题是,除了说明符限定符列表错误之外,我还收到一个新的但类似的错误。某些代码行在 *token 之前给出了 Expected a ')'
或 Expected a ';'在* token
之前。这些行通常也会给我以前的错误,所以 @class 技巧也有效,但我一点也不知道为什么这个东西会这样做。我在某处读到(我认为是 cocos2d 论坛),将 .m 文件重命名为 .mm 可能可以解决问题,但它不适合我。
所以,虽然我可以继续我的项目,但我真的很想知道将来如何避免类似的事情......
最佳答案
请检查是否存在循环依赖,例如在ClassA.h
中导入ClassB.h
,反之亦然。这是发生“Expected specifier-qualifier-list before...”错误的典型场景。
我建议在头文件中仅使用@class
,除了:
#import
父类(super class)#import
您的类实现的协议(protocol)
头文件应该在您的实现文件中进行#import
编辑。
"The Objective-C Programming Language"说:
The
@class
directive minimizes the amount of code seen by the compiler and linker, and is therefore the simplest way to give a forward declaration of a class name. Being simple, it avoids potential problems that may come with importing files that import still other files. For example, if one class declares a statically typed instance variable of another class, and their two interface files import each other, neither class may compile correctly.
更多引用:
关于iPhone cocos2d "Expected specifier-qualifier-list before ..."等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10337356/