Cocos2d:如何在场景之间共享播放器数据

时间:2012-07-24 17:33:00

标签: ios objective-c cocoa-touch cocos2d-iphone singleton

我有一个从CCNode派生的PlayerData类,我想在游戏的各个场景之间作为静态单例实例进行分享。

我尝试了以下实现:

#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface PlayerData : CCNode {

}

@property (readwrite, nonatomic) int data;  
+(id) playerData;
+(PlayerData*) sharedPlayerData;

#import "PlayerData.h"
@implementation PlayerData
@synthesize data;
static PlayerData* instanceOfPlayerData;

+(id) playerData 
{
    if(instanceOfPlayerData==nil){
        return  [[self alloc] init];
    }else {
        return [self sharedPlayerData];
    }
}

+(PlayerData*) sharedPlayerData{
    NSAssert(instanceOfPlayerData != nil, @"PlayerData instance not yet initialized!");
    return instanceOfPlayerData;
}


-(id) init 
{
    if ((self = [super init]))
    {
        instanceOfPlayerData=self;
        data=0;
        }
    return self;
}
@end

分配这个的正确位置在哪里?我考虑过添加并访问它到AppDelegate类,但我无法理解如何。

我从sharedDirector中看到我可以访问delagate值,但我不认为是正确的,除非我必须将它强制转换为我的AppDelegate类。有什么建议吗?

[[CCDirector sharedDirector] delegate];

这是我的AppDelegate类,来自模板:

#import <UIKit/UIKit.h>
#import "cocos2d.h"

@interface AppController : NSObject <UIApplicationDelegate, CCDirectorDelegate>
{
    UIWindow *window_;
    UINavigationController *navController_;

    CCDirectorIOS   *__unsafe_unretained director_;                         // weak ref
}

@property (nonatomic) UIWindow *window;
@property (readonly) UINavigationController *navController;
@property (unsafe_unretained, readonly) CCDirectorIOS *director;

@end

PS:我正在使用启用了ARC的Cocos2d v2.x

1 个答案:

答案 0 :(得分:2)

这是我用于游戏的一个很棒的单例教程,效果很好:http://getsetgames.com/2009/08/30/the-objective-c-singleton/