如果我有一个自定义类Person,它有三个变量(属性化和合成):
NSString* theName;
float* theHeight;
int theAge;
人员实例存储在NSArray“组”中。只有一个集团。在NSUserDefaults中存储和加载组的最佳方法是什么? (请记住,浮动和int对于NSUserDefaults来说是不合法的)
答案 0 :(得分:45)
@Brad Smith的回答并不完整,甚至在某种意义上也是错误的。我们必须使用NSKeyedArchiver
和NSKeyedUnarchiver
,如下所示:
使您的类(例如在本例中为Person
)符合协议NSCoding
并将这两种方法实现为:
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if(self) {
self.name = [decoder decodeObjectForKey:<key_for_property_name>];
// as height is a pointer
*self.height = [decoder decodeFloatForKey:<key_for_property_height>];
self.age = [decoder decodeIntForKey:<key_for_property_age>];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.name forKey:<key_for_property_name>];
//as height is a pointer
[encoder encodeFloat:*self.height forKey:<key_for_property_height>]
[encoder encodeInt:self.age forKey:<key_for_property_age>];
}
使用NSUserDefaults
// Write to NSUserDefaults
NSData *archivedObject = [NSKeyedArchiver archivedDataWithRootObject:<your_class_object>];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:archivedObject forKey:<key_for_archived_object>];
[defaults synchronize];
// Read from NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *archivedObject = [defaults objectForKey:<key_for_archived_object>];
<your_class> *obj = (<your_class> *)[NSKeyedUnarchiver unarchiveObjectWithData:archivedObject];
答案 1 :(得分:1)
我发现实现encodeWithCoder和initWithCoder非常无聊,特别是如果你的类中有很多属性,并且有许多类要保存到NSUserDefaults。
我创建了一个库RMMapper(https://github.com/roomorama/RMMapper)来帮助将自定义对象保存到NSUserDefaults中更方便,更方便。
要将类标记为可存档,只需使用:#import "NSObject+RMArchivable.h"
将自定义对象保存到NSUserDefaults:
#import "NSUserDefaults+RMSaveCustomObject.h"
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults rm_setCustomObject:user forKey:@"SAVED_DATA"];
从NSUserDefaults获取自定义obj:
user = [defaults rm_customObjectForKey:@"SAVED_DATA"];