【问题标题】:cannot init a class object : objective-C无法初始化类对象:objective-C
【发布时间】:2014-10-07 12:27:51
【问题描述】:

我正在尝试创建一个简单的 CCNode 子类,但我无法创建对象。

它给了我错误“* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* +[ContentPane init]: cannot init a class object.'”

这是我的 CCNode 子类:

#import "ContentPane.h"

@implementation ContentPane{
    int content[8][4];
    CCSprite *_rockPath1;
    CCSprite *_rockPath2;
}

- (id)init {
    self = [super init];

    if (self) {
        CCLOG(@"ContentPane created");
    }

    return self;
}

@结束

这是我尝试启动它的地方:

- (void)didLoadFromCCB {
    // tell this scene to accept touches
    self.userInteractionEnabled = TRUE;
    _counter = 0;
    ContentPane *pane = [ContentPane init];
}

【问题讨论】:

    标签: objective-c cocos2d-iphone subclass init


    【解决方案1】:

    几件事,

    在 Obj-c 中,当你要初始化一个 Object 时,你需要为它分配空间。 这是使用 alloc 关键字完成的。

    所以你的ContentPane *pane = [ContentPane init];

    变成ContentPane *pane = [[ContentPane alloc] init];

    此外,无论您遵循什么教程,停止...您声明变量的方式我们称之为变量 (iVars) 是一种非常老式的做事方式,它们应该是真正的属性。和 Boolean 值由 YESNO 表示,而不是 TRUEFALSE

    【讨论】:

    • 我以后是否必须释放我的对象?我对 ARC 能做什么和不能处理什么感到困惑。
    • 当然,Beginning iOS programming by Ray Wenderlich 是一个非常好的资源。任何不到一岁的书也会有帮助。自“旧”时代以来,Objective-c 已经成熟了很多。 ARC你一般不用担心,如果你使用properties,properties可以免费为你做很多事情。 ARC(自动引用计数)就是这样,如果一个属性被标记为Strong,那么它将增加引用计数,当该计数变为零时,您的对象将被释放
    【解决方案2】:

    如果你和我一样想知道你的代码为什么会崩溃。

     [NSArray init];
    

    应该是:

    [[NSArray alloc] init];
    

    [NSArray array];
    

    你的崩溃可能是其他任何类造成的,这里的NSArray仅供参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      相关资源
      最近更新 更多