我正在使用《Learning Cocos2D》一书中的模式。我有一个 GameState 类,它是一个可以保存为状态的单例。第一次创建类 gest 时,BOOL soundOn 将 init 设置为 false,但数组 levelProgress 不存在。我对尝试初始化数组的所有行发表了评论。该类使用加载和保存数据的助手。当我尝试 1 或 2 时,我得到“在类方法中访问的实例变量 'levelProgress'”错误。
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface GameState : NSObject <NSCoding> {
BOOL soundOn;
NSMutableArray *levelProgress;
}
+ (GameState *) sharedInstance;
- (void)save;
@property (assign) BOOL soundOn;
@property (nonatomic, retain) NSMutableArray *levelProgress;
@end
#import "GameState.h"
#import "GCDatabase.h"
@implementation GameState
@synthesize soundOn;
@synthesize levelProgress;
static GameState *sharedInstance = nil;
+(GameState*)sharedInstance {
@synchronized([GameState class])
{
if(!sharedInstance) {
sharedInstance = [loadData(@"GameState") retain];
if (!sharedInstance) {
[[self alloc] init];
// 1. levelProgress = [[NSMutableArray alloc] init];
}
}
return sharedInstance;
}
return nil;
}
+(id)alloc
{
@synchronized ([GameState class])
{
NSAssert(sharedInstance == nil, @"Attempted to allocate a \
second instance of the GameState singleton");
sharedInstance = [super alloc];
// 2. levelProgress = [[NSMutableArray alloc] init];
return sharedInstance;
}
return nil;
}
- (void)save {
saveData(self, @"GameState");
}
- (void)encodeWithCoder:(NSCoder *)encoder {
// 3. levelProgress = [[NSMutableArray alloc] init];
[encoder encodeBool:currentChoosenCountry forKey:@"soundOn"];
[encoder encodeObject:levelProgress forKey:@"levelProgress"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if ((self = [super init])) {
// 4. levelProgress = [[NSMutableArray alloc] init];
soundOn = [decoder decodeBoolForKey:@"soundOn"];
levelProgress = [decoder decodeObjectForKey:@"levelProgress"];
}
return self;
}
@end
解决方案: *我刚刚添加了 av init 方法... *
-(id)init {
self = [super init];
if (self != nil) {
levelProgress = [[NSMutableArray alloc] init];
}
return self;
}