我知道你必须使用 NSCoding 来存储自定义对象。
如在我的示例中,我有一个类 Game 并且我正在使用此 NSCoding 方法对其进行编码和解码
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:[NSNumber numberWithInt:turnTime] forKey:@"turnTime"];
[aCoder encodeObject:[NSNumber numberWithBool:time] forKey:@"extra"];
[aCoder encodeObject:[NSNumber numberWithBool:saved] forKey:@"saved"];
[aCoder encodeObject:dragon forKey:@"dragon"];
[aCoder encodeObject:playerJokers forKey:@"playerJokersKey"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
turnTime=[[aDecoder decodeObjectForKey:@"turnTime"] integerValue];
dragon=[aDecoder decodeObjectForKey:@"dragon"];
time=[[aDecoder decodeObjectForKey:@"extra"] boolValue];
saved=[[aDecoder decodeObjectForKey:@"saved"] boolValue];
playerJokers=[aDecoder decodeObjectForKey:@"playerJokersKey"];
return self;
}
保存游戏数据
-(void)saveGameData
{
NSLog(@"saveGameData");
NSUserDefaults * userdefaults=[NSUserDefaults standardUserDefaults];
NSData * gameData=[NSKeyedArchiver archivedDataWithRootObject:self];
[userdefaults setObject:gameData forKey:@"gameKey"];
[userdefaults synchronize];
}
如所见这种方法;您可以将自定义类转换为 NSData 并将其添加到 NSArray。
当你想使用它时;恢复数组,你有一个包含汽车数据的数组。
当我想使用保存的数据时
Game * savedGame=[NSKeyedUnarchiver unarchiveObjectWithData:gameData];