使用NSData进行键值对归档:
//
// main.m
// storeDemo_NSdata
//
// Created by 5016 on 13-12-18.
// Copyright (c) 2013年 dradon. All rights reserved.
//
#import <Foundation/Foundation.h>
//使用NSData进行归档存储
//归档
void store()
{
//1.获取路径
NSString *homePath = NSHomeDirectory();
NSString *targetPath = [homePath stringByAppendingPathComponent:@"Desktop/arr1.archive"];
//2.准备数据
NSMutableData *data = [NSMutableData data];
//3.归档
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
[archiver encodeInt:23 forKey:@"age"];
[archiver encodeObject:@"dragon" forKey:@"name"];
[archiver finishEncoding];//结束编码
[archiver release];
//4.写入文件
BOOL success = [data writeToFile:targetPath atomically:YES];
if (success) {
NSLog(@"归档成功");
}
else
{
NSLog(@"归档失败");
}
}
//解档
void readstore()
{
//1.获取路径
NSString *homePath = NSHomeDirectory();
NSString *targetPath = [homePath stringByAppendingPathComponent:@"Desktop/arr1.archive"];
//2.读取文件
NSData *data = [NSData dataWithContentsOfFile:targetPath];
//3.解档
NSKeyedUnarchiver *unachiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
//4.读取解档文件
int age = [unachiver decodeIntForKey:@"age"];
NSString *name = [unachiver decodeObjectForKey:@"name"];
NSLog(@"age = %d , name = %@",age,name);
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
store();
readstore();
}
return 0;
}