Person.h
#import
@interface Person : NSObject<</span>NSCoding>
@property(nonatomic, copy)NSString *name;
@property(nonatomic, assign)int age;
@end
Person.m
#import "Person.h"
@implementation Person
// 遵循NSCoding协议
- (void)encodeWithCoder:(NSCoder *)aCoder
{
//[super encodeWithCoder:aCoder];// 如果其他类继承该类需调用super方法
[aCoder encodeInt:self.age forKey:@"age"];
[aCoder encodeObject:self.name forKey:@"name"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
//[super initWithCoder:aDecoder]; // 如果其他类继承该类需调用super方法
self.age = [aDecoder decodeIntForKey:@"age"];
self.name = [aDecoder decodeObjectForKey:@"name"];
return self;
}
@end
对象归档和解档:
/**
@ 单对象的存储
*/
Person *person = [[Person alloc] init];
person.name = @"xiaoming";
person.age = 11;
// document路径
NSString *path3= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// 创建.archiver文件,该后缀名可以随意命名
NSString *path4 = [path3 stringByAppendingPathComponent:@"person.archiver"];
// 对象归档
[NSKeyedArchiver archiveRootObject:person toFile:path4];
// 解档1
Person *per = [NSKeyedUnarchiver unarchiveObjectWithFile:path4];
NSLog(@"%@-%d",per.name,per.age);
/**
@ 多对象的存储
*/
// 对象1
Person *dahong = [[Person alloc] init];
dahong.name = @"dahong";
dahong.age = 33;
// 对象2
Person *xiaohua = [[Person alloc] init];
xiaohua.name = @"xiaohua";
xiaohua.age = 55;
// 归档
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *arch = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[arch encodeObject:xiaohua forKey:@"person1"];
[arch encodeObject:dahong forKey:@"person2"];
[arch finishEncoding]; // 完成编码
// data写入路径下
NSString *personPath = [path3 stringByAppendingPathComponent:@"person.data"];
[data writeToFile:personPath atomically:YES];
/**
@ 多对象读取
*/
NSURL *url = [NSURL fileURLWithPath:personPath];
//[NSData dataWithContentsOfFile:<#(NSString *)#>]; 此方法也可以
NSData *undata = [NSData dataWithContentsOfURL:url];
NSKeyedUnarchiver *unarch = [[NSKeyedUnarchiver alloc] initForReadingWithData:undata];
Person *unp1 = [unarch decodeObjectForKey:@"person1"];
Person *unp2 = [unarch decodeObjectForKey:@"person2"];
// 完成
[unarch finishDecoding];
NSLog(@"%@%@",unp1,unp2);
/**
@ 归档解档实现对象深copy
*/
Person *copyPer = [[Person alloc] init];
copyPer.age = 23;
copyPer.name = @"aaaa";
// 转成data
NSData *copyDa = [NSKeyedArchiver archivedDataWithRootObject:copyPer];
// 解档
Person *copyPer2 = [NSKeyedUnarchiver unarchiveObjectWithData:copyDa];
// 此时copyPer和copyPer2对象内存地址不一样,完成了深copy