Im am using a pattern from the book Learning Cocos2D. I have a GameState class that is a singleton that can be saved as a state. The BOOL soundOn gets init as false the first time the class gest created, but the array levelProgress dosent. I made comments on all the lines on which I have tried to init the array.
The class uses a helper that loads and saves the data.
When i try 1 or 2 i get “instance variable ‘levelProgress’ accessed in class method” error.
#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
Solution:
*I just added av init method…*
-(id)init {
self = [super init];
if (self != nil) {
levelProgress = [[NSMutableArray alloc] init];
}
return self;
}
Try this (this code may contain syntax or logic errors – I wrote it in notepad):
//