标签:
前言:
前天学习了NSUserDefaults,我们知道NSUserDefaults不能保存自定义对象,所以我们今天来认识一下归档和解档。我们先来回顾一下JAVA是怎么实现保存一个自定义对象的!首先一个自定义对象必须实现Serializable接口,然后把一个对象序列化成二进制数据写入一个byte[]数据或者文件,反之则是从一个二进制数据或者文件中读取二进制数据反序列化成对象,所以我认为ios的归档解档其实就是类似JAVA序列化反序列化的过程,下面写个程序来尝试一下。
先测试下基础类型:
//归档 NSString *Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; //字符串数据 NSString * string =@"who is lcj?"; NSString *filename = [Path stringByAppendingPathComponent:@"testString"]; [NSKeyedArchiver archiveRootObject:string toFile:filename]; NSString *string1=[NSKeyedUnarchiver unarchiveObjectWithFile:filename]; NSLog(@"testString---%@",string1); //集合数组 NSMutableArray *array = [NSMutableArray arrayWithObjects:@"who", @"islcj", nil]; filename = [Path stringByAppendingPathComponent:@"testArray"]; [NSKeyedArchiver archiveRootObject:array toFile:filename]; NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile: filename]; NSLog(@"testArray---%@",arr); //字典保存 filename = [Path stringByAppendingPathComponent:@"testNSDictionary"]; NSDictionary *dictionary=[NSDictionary dictionaryWithObject:@"whoislcj" forKey:@"name"]; [NSKeyedArchiver archiveRootObject:dictionary toFile:filename]; NSDictionary *dictionary1=[NSKeyedUnarchiver unarchiveObjectWithFile: filename]; NSLog(@"dictionary---%@",dictionary1);
上面已经说了JAVA要想实现序列化反序列化必须实现Serializable接口,那么iOS呢?iOS需要实现NSCoding协议,
Person.h
#import <Foundation/Foundation.h> @interface Person : NSObject<NSCoding> @property (nonatomic,strong)NSString *name; @end
Person.m
#import "Person.h" @implementation Person #pragma mark - NSCoding Delegate - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.name forKey:@"name"]; } - (id)initWithCoder:(NSCoder *)aDecoder { self.name = [aDecoder decodeObjectForKey:@"name"]; return self; } @end
具体实现:
//自定义对象类型 Person *person=[[Person alloc]init]; person.name=@"whoislcj"; filename = [Path stringByAppendingPathComponent:@"testObject"]; [NSKeyedArchiver archiveRootObject:person toFile:filename]; Person *tempPerson = [NSKeyedUnarchiver unarchiveObjectWithFile: filename]; NSLog(@"tempPerson:%@",tempPerson.name);
归档如何删除
//删除归档文件 NSFileManager *defaultManager = [NSFileManager defaultManager]; if ([defaultManager isDeletableFileAtPath:filename]) { [defaultManager removeItemAtPath:filename error:nil]; }
缺点:归档的形式来保存数据,只能一次性归档保存以及一次性解压。所以只能针对小量数据,而且对数据操作比较笨拙,即如果想改动数据的某一小部分,还是需要解压整个数据或者归档整个数据。
IOS数据存储之归档(NSKeyedArchiver)/解档(NSKeyedUnarchiver)
标签:
原文地址:http://www.cnblogs.com/whoislcj/p/5481123.html