简单示例归档与解档的过程

来源:互联网 发布:指南针软件 不断打电话 编辑:程序博客网 时间:2024/06/05 06:29

演示将一个字典类型归档到文件和从文件解档的过程。

////  main.m/* 演示将一个字典类型进行归档和解档的过程 */#define PATH @"/Users/apple/Documents/ios_dev/test_case/TestNSArchive/dic.plist"#import <Foundation/Foundation.h>int main(int argc, const char * argv[]) {    @autoreleasepool {        /* 归档:将数据写入文件 */                NSDictionary *dic = @{@"key1":@"value1", @"key2":@"value2", @"key3":@"value3"};                /* archivedDataWithRootObject:Returns a data object containing the encoded form of the          object graph whose root object is given. */        NSData *data = [NSArchiver archivedDataWithRootObject:dic]; /* NSDictionary->NSData */                /* writeToFile:Writes the bytes in the receiver to the file specified by a given path. */        BOOL ret = [data writeToFile:PATH atomically: YES];        if (ret == 0)        {            NSLog(@"write fail.");            return 0;        }                        /* 解档:方法1 */                /* unarchiveObjectWithFile:Decodes and returns the object archived in the file path.*/        id obj;        obj = [NSUnarchiver unarchiveObjectWithFile:PATH]; /* path->id */        NSLog(@"first:%@",obj);                        /* 解档:方法2 */                /* unarchiveObjectWithData:Decodes and returns the object archived in a given NSData object.*/        NSData *data2 = [NSData dataWithContentsOfFile:PATH]; /* path->NSData */        obj = [NSUnarchiver unarchiveObjectWithData:data2]; /* NSData->id */        NSLog(@"second:%@", obj);            }    return 0;}
输出结果:

2015-12-12 21:59:03.075 TestNSArchive[510:15924] first:{    key1 = value1;    key2 = value2;    key3 = value3;}2015-12-12 21:59:03.076 TestNSArchive[510:15924] second:{    key1 = value1;    key2 = value2;    key3 = value3;}


0 0