Objective-C Cocos2D-iPhone:单例图层及其场景

时间:2018-07-05 18:31:04

标签: objective-c cocos2d-iphone

我对“ ScoreboardLayer”层有一个单例类, 及其场景工厂如下。在我的项目中多次使用场景时,它会崩溃。崩溃错误消息是“原因:'子项已添加。不能再次添加'”。我猜这是因为在Scene工厂中添加的图层是单例类,并且自从在项目中首次调用Scene以来就已经存在。但是Scene容器不是单例类,所以我不明白为什么它会崩溃。无论如何,如何制作具有Singleton图层的Singleton Scene容器?谢谢。

@implementation ScoreboardLayer

+(CCScene *) scene{
    CCScene* scene = [CCScene node];
    ScoreboardLayer* layer = [ScoreboardLayer sharedScoreboardLayer];

    [scene addChild:layer];  // <<<=== crash w/ error msg: reason: 'child already added. It can't be added again'
    return scene;
}

// singleton class factory
+(ScoreboardLayer *) sharedScoreboardLayer{
    static dispatch_once_t once;
    static ScoreboardLayer* sharedScoreboardLayerInstance;

    dispatch_once( &once,
              ^{ sharedScoreboardLayerInstance = [[self alloc] init];} );

    return sharedScoreboardLayerInstance;
}

// ........

@end

0 个答案:

没有答案