保存到自定义类的nsuserdefaults的最佳方法? [英] Best way to save to nsuserdefaults for custom class?

查看:117
本文介绍了保存到自定义类的nsuserdefaults的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a custom class Person which has three variables (which are propertized and synthesized):

NSString* theName;
float* theHeight;
int theAge;

人物实例存储在NSArray群组中。只有一个集团。在NSUserDefaults中存储和加载组的最佳方法是什么? (铭记浮动,INT是不合法的NSUserDefaults的)

Person instances are stored in an NSArray 'Group'. There is only one Group. What is the best way of storing and loading the Group in NSUserDefaults? (bearing in mind that float and int are not legal for NSUserDefaults)

推荐答案

@Brad史密斯的答案是不完整的,甚至是在某种意义上不正确。我们必须使用的NSKeyedArchiver NSKeyedUnarchiver 如下:

@Brad Smith's answer is not complete, and even is incorrect in some sense. We have to use NSKeyedArchiver and NSKeyedUnarchiver as follows:

使你的类(例如在这种情况下 Person )符合协议 NSCoding 并将这两个方法实现为:

Make your class (for example in this case Person) to conform to protocol NSCoding and implement both the methods as:

- (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];

这篇关于保存到自定义类的nsuserdefaults的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆