iOS 存取数据方式之归档

2016-10-08  本文已影响29人  MissZhou_周小小

遵循NSCoding协议

NSCoding协议声明了两个方法,这两个方法是一定要实现的。其中一个方法用来说明如何将对象编码到归档中,另一个方法用来说明如何进行解档获取新对象。

1.  遵循协议和设置属性
@interface Student : NSObject<NSCoding>
/* 姓名 */
@property(nonatomic,copy)NSString *name;
/* 年龄 */
@property(nonatomic,assign)NSInteger age;
/* 身高 */
@property(nonatomic,assign)double height;

2. 实现协议方法一(归档,保存数据)
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
    [aCoder encodeDouble:self.height forKey:@"height"];
}
3. 实现协议方法二(解档,读取数据)
- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntegerForKey:@"age"];
        self.height = [aDecoder decodeDoubleForKey:@"height"];
    }
    return self;
}

使用

把对象归档是调用NSKeyedArchiver的工厂方法 archiveRootObject: toFile:

    NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"student.data"];
    Student *student = [[Student alloc] init];
    student.name = @"lily";
    student.age = 25;
    student.height = 166;
    [NSKeyedArchiver archiveRootObject:student toFile:savePath];

从文件中解档对象就调用NSKeyedUnarchiver的一个工厂方法 unarchiveObjectWithFile:

    NSString *readerPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"student.data"];
    Student *student = [NSKeyedUnarchiver unarchiveObjectWithFile:readerPath];
    if (student) {
        self.informationLable.text = [NSString stringWithFormat:@"该学生的姓名:%@,年龄:%ld,身高:%.2f",student.name,student.age,student.height];
    }

注意

必须遵循并实现NSCoding协议
保存文件的扩展名可以任意指定
继承时必须先调用父类的归档解档方法

具体参考

http://code.cocoachina.com/view/133063

上一篇 下一篇

猜你喜欢

热点阅读