我有一个来自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访问一个滞后值,但我认为这不是正确的方法,除非必须将其强制转换为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
最佳答案
这是我用于游戏的出色单例教程,并且效果很好:http://getsetgames.com/2009/08/30/the-objective-c-singleton/