gpt4 book ai didi

iphone - 为自定义类保存到 nsuserdefaults 的最佳方法?

转载 作者:太空狗 更新时间:2023-10-30 03:16:18 25 4
gpt4 key购买 nike

如果我有一个自定义类 Person,它具有三个变量(已属性化和合成):

NSString* theName;
float* theHeight;
int theAge;

Person 实例存储在 NSArray 'Group' 中。只有一个组。在 NSUserDefaults 中存储和加载组的最佳方式是什么? (记住 float 和 int 对于 NSUserDefaults 是不合法的)

最佳答案

@Brad Smith 的回答并不完整,甚至在某种意义上是不正确的。我们必须使用 NSKeyedArchiverNSKeyedUnarchiver 如下:

使您的类(例如在本例中为 Person)符合协议(protocol) 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];

关于iphone - 为自定义类保存到 nsuserdefaults 的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3000220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com