Cocos2d iphone 无法通过单例访问阵列

Cocos2d iphone 无法通过单例访问阵列,cocos2d-iphone,singleton,Cocos2d Iphone,Singleton,我需要将一个数组从InGameLayer传递给AppDelegate,下面是我所做的 在InGameLayer.h @interface InGameLayer : CCLayer @property (nonatomic, strong) CCArray *heroArray; +(InGameLayer *)sharedInGameLayer; 在InGameLayer.m static InGameLayer* sharedInGameLayer; +(InGameLayer*)shar

我需要将一个数组从InGameLayer传递给AppDelegate,下面是我所做的

在InGameLayer.h

@interface InGameLayer : CCLayer
@property (nonatomic, strong) CCArray *heroArray;
+(InGameLayer *)sharedInGameLayer;
在InGameLayer.m

static InGameLayer* sharedInGameLayer;
+(InGameLayer*)sharedInGameLayer
{
    if (sharedInGameLayer == nil)
    {
        sharedInGameLayer = [[self alloc] init];
    }
    return sharedInGameLayer;
}

//add Object if the button is tapped
- (void)PlayerButton1Tapped:(id)sender
{
    CCSprite *hero =[CCSprite spriteWithFile:@"hero.png"];
    [_heroArray addObject:hero];
}
在AppDelegate.m中

-(void) applicationDidEnterBackground:(UIApplication*)application
{
    CCArray *heroArray = [InGameLayer sharedInGameLayer].heroArray;
    CCLOG(@"array = %d", heroArray.count);
}
问题是数组=0,不管我在数组中添加了多少对象。
请帮我解决这个问题。提前感谢您的时间。

您从未创建过阵列。属性声明自动合成实例变量
CCArray*\u heroArray
及其访问方法。所有实例变量在创建对象时都用零初始化,并且由于您从未在实例变量中存储指向实际CCArray对象的指针,因此它将保持为
nil

在类的
init
方法中,您应该执行以下操作

_heroArray = [[CCArray alloc] init];

嗨,是的,我在我的init方法中有这样的init数组。问题是我没有在init方法中添加我的对象。我想让用户通过单击按钮添加对象。并且对象永远不会传递给AppDelegate(AppDelegate中的数组为nil)。你能给我一个建议吗?谢谢你的回复