iOS OC C

数据持久化

归档

920 发布: 2015/12/6 09:56 本文总阅读量

直接代码

#import "ViewController.h"

#import "Student.h"

#define __DOCUMENTS_PATH__ [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    //-->归档

    NSLog(@"%@",__DOCUMENTS_PATH__);

    //创建归档对象,这个对象可以把数据压入mutableData。

    NSMutableData *mutableData = [NSMutableData data];

    //自定义的初始化方法必须指定可变的data

    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mutableData];
    Student *stu = [[Student alloc]init];
    stu.name = @"Jack";
    stu.age = @"25";
    [archiver encodeObject:stu forKey:@"student"];
    [archiver finishEncoding];
    NSString *archiverPath = [__DOCUMENTS_PATH__ stringByAppendingPathComponent:@"student.plist"];
    BOOL isOk = [mutableData writeToFile:archiverPath atomically:YES];
    NSLog(@"%d",isOk);

    //-->解归档

    NSData *getData = [NSData dataWithContentsOfFile:archiverPath];
    if (getData.length) {

        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:getData];
        Student *getStu = [unarchiver decodeObjectForKey:@"student"];
        NSLog(@"解归档:%@---%@",getStu.name,getStu.age);

    }
}
@end

新浪博客的图片丢失了

新浪博客的原始图片丢失了

说明:控制台打印为文件路径归档数据文件后缀我写作了.plist是为了方便打开,一般后缀写成不能打开的后缀名左边为归档数据plist。归档类(Student)要遵守NSCoding协议并实现里面的两个必实现方法。