从文档:
默认对象必须是一个属性列表,即以下实例(或集合实例的组合):NSData、NSString、NSNumber、NSDate、NSArray 或 NSDictionary。
为了存储另一种类型的对象,您首先需要在要存储的对象的类中实现 NSCoding 协议。这意味着实现这些方法并像这样进行解码和编码(我自己的自定义类 BMDifficultyLevel 的代码片段):
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
_difficultyLevel = [decoder decodeObjectForKey:@"difficulty"];
_difficultyLevelType = [decoder decodeIntegerForKey:@"type"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:_difficultyLevel forKey:@"difficulty"];
[encoder encodeInteger:_difficultyLevelType forKey:@"type"];
}
然后在存储您的对象之前,您需要存档,然后像这样存储:
NSUserDefaults *defaults = [[NSUserDefaults alloc] init];
_defaultsDataWithLevelObject = [NSKeyedArchiver archivedDataWithRootObject:_difficultyLevel];
[defaults setObject:_defaultsDataWithLevelObject forKey:BMDifficultyLevelDefaultsKey];
where_defaultsDataWithLevelObject
是 NSData 类型的对象,这意味着您最终会存储 NSData 对象。
要检索您的默认值,您需要像这样取消归档对象:
_defaultsDataWithLevelObject = [[NSUserDefaults standardUserDefaults] objectForKey:BMDifficultyLevelDefaultsKey];
_difficultyLevel = [NSKeyedUnarchiver unarchiveObjectWithData:_defaultsDataWithLevelObject];