5/05/2009

NSKeyedUnarchiver

Using NSKeyedUnarchiver to save player data and item data as an alternative to NSUserDefaults. I've read that NSUserDefaults isn't the best for storing huge amounts of data. Actually, the reason I migrated to NSKeyedUnarchiver is because I couldn't save some object or an array using NSUserDefaults. Now I can save the items I've purchased from the store. Learned how to use enum.
プレイヤーデータ、アイテムデータなどはNSUserDefaultsじゃなくてArchiverでセーブ。買ったアイテムをセーブできるようになった。enumの使い方もおぼえた。



theData = [NSData dataWithContentsOfFile:dataFilePath];
decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];
Player *tempPlayer = [decoder decodeObjectForKey:@"playerData"];


- (void)savePlayerStateBeforeTerminate {
Player *player = [Player getInstance];
Player *tempPlayer = [[Player alloc] init];
tempPlayer = player;
NSMutableData *theData;
NSKeyedArchiver *encoder;
theData = [NSMutableData data];
encoder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:theData];
[encoder encodeObject:tempPlayer forKey:@"playerData"];
[encoder finishEncoding];
[theData writeToFile:dataFilePath atomically:YES];
[encoder release];
}


Player.m

- (id)initWithCoder:(NSCoder *)decoder
{
playerLevel = [decoder decodeIntegerForKey:@"playerLevel"];
playerFloor = [decoder decodeIntegerForKey:@"playerFloor"];
playerRoom = [decoder decodeIntegerForKey:@"playerRoom"];
...
return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
//[super encodeWithCoder:coder];
[coder encodeInt:playerLevel forKey:@"playerLevel"];
[coder encodeInt:playerFloor forKey:@"playerFloor"];
...
}

No comments:

Post a Comment