归档

归档

归档就是将我们所使用的变量或者对象以一定的格式写入文件进行存储,等到需要的时候读出来进行还原。

代码展示:

#define PATH @"/Users/md101/Desktop"

#define ERROR(A) if(A){NSLog(@"%@",A);}

int main ()

{

    @autoreleasepool {


       //将字典中的内容写入文件

        /*NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3", nil];

        [dict writeToFile:[NSString stringWithFormat:@"%@/testfile/temp.m",PATH] atomically:YES];

        //将文件中的内容读入字典

        NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/testfile/temp.m",PATH]];

        NSLog(@"%@",dict);*/

        //当有大量的对象或数组等需要进行归档时需要使用辅助的NSKeyedArchieve

        //将数组与字典归档到同一个文件中

        NSArray *array = [[NSArray alloc] initWithObjects :@"one",@"two",@"three",nil];

        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3", nil];

        NSMutableData *date = [[NSMutableData alloc] init];

        //archiver相当于一个管理员将多个对象或数组等连在一起,放到date库中

        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:date];

        [archiver encodeObject:array forKey:@"array"];

        [archiver encodeObject:dict forKey:@"dict"];

        [archiver finishEncoding];

        [date writeToFile:[NSString stringWithFormat:@"%@/testfile/temp1.m",PATH] atomically:YES];

        //从文件中读取多个数组或者对象

        date = [[NSMutableData alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/testfile/temp1.m",PATH]];

        NSKeyedUnarchiver *unarhiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:date];

        NSArray *array1 = [unarhiver decodeObjectForKey: @"array"];

        NSLog(@"%@",array1);

    }

    

    return 0;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值