views:

33

answers:

1

Hello All,

I've used the following example:

http://stackoverflow.com/questions/2670815/game-state-singleton-cocos2d-initwithencoder-always-returns-null

Instead of using a file, I use an NSData object i am getting from NSUserDefaults. It is not null, but rather have data in it that I believe is the correctly encoded data and for some reason when I run unarchiveObjectWithData it does not call initWithCoder as I put an NSLog on the first line.

Ideas?

+ (void)loadState {
 @synchronized([AppStateManager class]) {
  if (!sharedAppStateManager) {
   [AppStateManager sharedManager];
  }

  NSUserDefaults *udefs = [NSUserDefaults standardUserDefaults];
  NSData *archivedData = [udefs objectForKey:@"AppState"];
  NSLog(@"going to unarchive");
  [NSKeyedUnarchiver unarchiveObjectWithData:archivedData];
  NSLog(@"unarchive complete");
 }
}

- (id)initWithCoder:(NSCoder *)decoder {
 NSLog(@"init coder");
 self = [super init];
 if (self != nil) {
  [self setUsername:[decoder decodeObjectWithKey:@"username"]];
 }

 return self;
}
A: 

Solved.

The example posted at the link above initializes the object via "sharedInstance" using the allocWithZone method. If the object exists it returns nil.

the NSKeyedUnarchiver tries to alloc AGAIN via allocWithZone and since the object has already been initialized earlier in that very same method, or sometimes before hand the unarchiver gets a nil instead of an allocated object.

Hope this helps someone.

schone