私は本LearningCocos2Dのパターンを使用しています。状態として保存できるシングルトンのGameStateクラスがあります。BOOL soundOnは、クラスgestが最初に作成されたときにfalseとして初期化されますが、配列levelProgressはdosentです。配列を初期化しようとしたすべての行にコメントを付けました。このクラスは、データをロードおよび保存するヘルパーを使用します。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
解決策: * avinitメソッドを追加しました... *
-(id)init {
self = [super init];
if (self != nil) {
levelProgress = [[NSMutableArray alloc] init];
}
return self;
}