objc对象归档(序列化)

概念:归档是把对象写入文件保存在硬盘中,当再次重新打开程序时,可以还原这些对象。
归档主要用到 NSKeyedArchiver 、 NSKeyedUnarchiver 两个类
NSKeyedArchiver 中使用archiveRootObject:toFile: 或者 archivedDataWithRootObject: 来归档类。
NSKeyedUnarchiver 中使用narchiveObjectWithFile: 或者 unarchiveObjectWithData: 来反归档类。

归档系统自带的类
因NSString、NSArray、NSData、NSDictionary 都实现了NSCoding协议,可直接通过调用writeToFile归档。
NSString *str = @"hello";
[str writeToFile:@"/Users/sdh/Desktop/str.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];

NSArray *arr = [[NSArray alloc]initWithObjects:@"lili",@"tata", nil];
NSURL *localUrl = [NSURL fileURLWithPath:@"/Users/sdh/Desktop/arr.txt"];//本地路径
[arr writeToURL:localUrl atomically:YES];//writeToURL相对writeToFile优势在于前者可以远程或本地,而后者只能本地
        
NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[@"lili",@"男"] forKeys:@[@"name",@"sex"]];
[dict writeToFile:@"/Users/sdh/Desktop/dict.txt" atomically:YES];

归档自定义的类
首先实现NSCoding协议,重写encodeWithCode方法和initWithCode方法,然后通过NSKeyedArchiver转换为NSData,再通过NSData的writeToFile方法写入到文件,
或者将转换后的NSData放入到NSArray或NSDictionary中调用writeToFile写入到文件便可实现包装了自定义类型的数据和字典的归档。

Person类定义
@interface Person : NSObject<NSCoding>//实现NSCoding协议
@property(assign,nonatomic)int age;
@property(copy,nonatomic)NSString *name;
@end

@implementation Person
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeInt:self.age forKey:@"age"];
    [aCoder encodeObject:self.name forKey:@"name"];
}
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
    if(self = [super init]) {
        self.age = [aDecoder decodeIntForKey:@"age"];
        self.name = [aDecoder decodeObjectForKey:@"name"];
    }
    return self;
}
@end

Person *aPerson = [[Person alloc]init];
aPerson.age = 20;
aPerson.name = @"sdh";

//归档   
NSData *aData =  [NSKeyedArchiver archivedDataWithRootObject:aPerson];
NSUserDefaults *uDefaults = [NSUserDefaults standardUserDefaults];//也可以将归档后的数据存储到NSUserDefaults数据库中
[uDefaults setObject:aData forKey:@"archive"];
[uDefaults synchronize];
//反归档     
NSData *personData = [uDefaults objectForKey:@"archive"];
Person *uPerson = [NSKeyedUnarchiver unarchiveObjectWithData:personData];

//自定义类与系统类组合一起
NSDictionary *dictPerson = [NSDictionary dictionaryWithObjects:@[[NSKeyedArchiver archivedDataWithRootObject:parent],[NSKeyedArchiver archivedDataWithRootObject:child]] forKeys:@[@"parent",@"child"]];  
[dictPerson writeToFile:@"/Users/lili/Desktop/dictPerson.txt" atomically:YES];  


      
NSDictionary *pdict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/lili/Desktop/dictPerson.txt"];//dictionaryWithContentsOfFile
Person *tPerson = [NSKeyedUnarchiver unarchiveObjectWithData:[pdict objectForKey:@"parent"]];  

NSArray *arrPerson = [[NSArray alloc]initWithObjects:[NSKeyedArchiver archivedDataWithRootObject:parent],[NSKeyedArchiver archivedDataWithRootObject:parent], nil];  
[arrPerson writeToFile:@"/Users/lili/Desktop/arrPerson.txt" atomically:YES];  

NSArray *pArr = [NSArray arrayWithContentsOfFile:@"/Users/lili/Desktop/arrPerson.txt"];//arrayWithContentsOfFile
Person *aPerson = [NSKeyedUnarchiver unarchiveObjectWithData:[pArr objectAtIndex:0]];  

采用encodeObject方式归档
Person *aPerson = <#Get a Person#>;
NSString *archivePath = <Path for the archive#>;
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:aPerson forKey:ASCPersonKey];
[archiver encodeInt:100 forKey:ASCNumKey];
[archiver finishEncoding];

NSURL *archiveURL = <URL for the archive#>;
BOOL result = [data writeToURL:archiveURL atomically:YES];

采用decodeObjectForKey方式反归档
NSURL *archiveURL = <URL for the archive#>;
NSData *data = [NSData dataWithContentsOfURL:archiveURL];
 
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
// Customize the unarchiver.
Person *aPerson = [unarchiver decodeObjectForKey:ASCPersonKey];
int num = [unarchiver decodeIntForKey:ASCNumKey];
[unarchiver finishDecoding];


类归档时,常用到文件的一些操作。总结如下
文件的创建
//设定文本框存储文件的位置
NSString *strFilePath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
//指定存储文件的文件名
NSString *fileName=[strFilePath stringByAppendingPathComponent:@"test.txt"];
//文件管理器
NSFileManager *fmaneger=[NSFileManager defaultManager]; 
if ([fmaneger fileExistsAtPath:[self getFilePath]]) 
{ 
    self.txtField.text=[NSString stringWithContentsOfFile:[self getFilePath] encoding:NSUTF8StringEncoding error:nil]; 
}

文件的写入
[self.txtField.text writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:nil];

文件的读取
NSFileManager *fmanager=[NSFileManager defaultManager];
if ([fmanager fileExistsAtPath:fileName]) { 
    [fmanager createFileAtPath:fileName contents:nil attributes:nil];
}


文件的移动
//目标文件夹
NSString *destPath=NSTemporaryDirectory();
//目标文件路径
NSString * destFilePath=[destPath stringByAppendingPathComponent:@"test.txt"];
BOOL result=[fmanager moveItemAtPath:filePath toPath:destFilePath error:nil];
if (result) {
    NSLog(@"移动成功");
}
else
{
    NSLog(@"移动失败!");
}

文件的删除
NSFileManager *fmanager=[NSFileManager defaultManager];
[fmanager removeItemAtPath:filePath error:nil];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值