基本的数据类型如NSString、NSDictionary、NSArray、NSData、NSNumber等可以用属性列表的方法持久化到.plist 文件中,但如果是一些自定义的类的话,属性列表的方法就不管用了。archiver 方法可以做到。
编码如下:
首先新建一个person类,定义它的三个属性,如下:
// // person.h // 数据持久化之archiver // // Created by Rio.King on 13-9-22. // Copyright (c) 2013年 Rio.King. All rights reserved. // #import <UIKit/UIKit.h> @interface person : UIView<NSCoding> @property(nonatomic, assign) int age; @property(nonatomic, copy)NSString *name; @property(nonatomic, assign)float height; @end
// // person.m // 数据持久化之archiver // // Created by Rio.King on 13-9-22. // Copyright (c) 2013年 Rio.King. All rights reserved. // #import "person.h" @implementation person #pragma mark 写入文件 -(void)encodeWithCoder:(NSCoder *)encoder{ [super encodeWithCoder:encoder];//不要忘了这个 [encoder encodeInt:self.age forKey:@"age"]; [encoder encodeObject:self.name forKey:@"name"]; [encoder encodeFloat:self.height forKey:@"height"]; } #pragma mark 从文件中读取 -(id)initWithCoder:(NSCoder *)decoder{ self = [super initWithCoder:decoder];//不要忘了这个 self.age = [decoder decodeIntForKey:@"age"]; self.name = [decoder decodeObjectForKey:@"name"]; self.height = [decoder decodeFloatForKey:@"height"]; return self; } -(NSString *)description{ return [NSString stringWithFormat:@"name = %@, age = %d, height = %f",self.name,self.age,self.height]; } //释放资源 -(void)dealloc{ [super dealloc]; [_name release]; } @end
然后再ViewController.m文件中写如下代码:
// // ViewController.m // 数据持久化之archiver // // Created by Rio.King on 13-9-22. // Copyright (c) 2013年 Rio.King. All rights reserved. // #import "ViewController.h" #import "person.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self createPerson]; [self readPerson]; } //创建 -(void)createPerson{ person *p = [[[person alloc] init] autorelease]; p.age = 20; p.name = @"Rio"; p.height =1.75f; //获得Document的路径 NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *path = [documents stringByAppendingPathComponent:@"person.archiver"];//拓展名可以自己随便取 [NSKeyedArchiver archiveRootObject:p toFile:path]; } //读取 -(void)readPerson{ NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *path = [documents stringByAppendingPathComponent:@"person.archiver"]; person *person1 = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; NSLog(@"%@",person1); } @end
在写ViewController.m文件代码的时候,必须在头文件中遵循NSCoding协议。
- #import <UIKit/UIKit.h>
- @interface ViewController : UIViewController<NSCoding>
- @end
运行结果如下:
2013-09-22 13:31:39.509 数据持久化之archiver[1080:c07] name = Rio, age = 20, height = 1.750000
注意事项:
1.遵循NSCoding协议
NSCoding协议声明了两个方法,这两个方法都是必须实现的。一个用来说明如何将对象编码到归档中,另一个说明如何进行解档来获取一个新对象。
-
遵循协议和设置属性
View Code//1.遵循NSCoding协议 @interface Person : NSObject <NSCoding> //2.设置属性 @property (strong, nonatomic) UIImage *avatar; @property (copy, nonatomic) NSString *name; @property (assign, nonatomic) NSInteger age; @end
-
实现协议方法
//解档 - (id)initWithCoder:(NSCoder *)aDecoder { if ([super init]) { self.avatar = [aDecoder decodeObjectForKey:@"avatar"]; self.name = [aDecoder decodeObjectForKey:@"name"]; self.age = [aDecoder decodeIntegerForKey:@"age"]; } return self; } //归档 - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.avatar forKey:@"avatar"]; [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeInteger:self.age forKey:@"age"]; }
2.使用
-
需要把对象归档是调用NSKeyedArchiver的工厂方法
archiveRootObject: toFile:方法。
View CodeNSString *file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"]; Person *person = [[Person alloc] init]; person.avatar = self.avatarView.image; person.name = self.nameField.text; person.age = [self.ageField.text integerValue]; [NSKeyedArchiver archiveRootObject:person toFile:file];
-
需要从文件中解档对象就调用NSKeyedUnarchiver的一个工厂方法
unarchiveObjectWithFile:即可。
View CodeNSString *file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"]; Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:file]; if (person) { self.avatarView.image = person.avatar; self.nameField.text = person.name; self.ageField.text = [NSString stringWithFormat:@"%ld", person.age]; }
3.注意
- 必须遵循并实现NSCoding协议
- 保存文件的扩展名可以任意指定
- 继承时必须先调用父类的归档解档方
- 如果需要归档的类是某个自定义类的子类时,就需要在归档和解档之前先实现父类的归档和解档方法。即
[super encodeWithCoder:aCoder]和[super initWithCoder:aDecoder]方法;
如果要归档Book类的子类对象,那么要在encodeWithCoder和decodeWithCoder方法中首先调用父类的编码和解码方法。这里要注意,如果在Book类中<NSCoding>协议声明在匿名类别中,那么协议的方法将是私有的,子类无法访问,因此要将<NSCoding>协议声明移到接口部分:
@interface Book () // <NSCoding> @end
修改为:
@interface Book : NSObject <NSCoding>
下面新建一个Book类的子类Literature类:
#import "Book.h" @interface Literature : Book <NSCoding> @property (copy, nonatomic) NSString *author; @end #import "Literature.h" static NSString *kAuthor = @"LiteratureAuthor"; @implementation Literature - (NSString *)description { NSString *bookDes = [super description]; NSString *literDes = [bookDes stringByAppendingFormat:@"Author = %@", self.author]; return literDes; } #pragma mark - NSCoding - (void)encodeWithCoder:(NSCoder *)aCoder { [super encodeWithCoder:aCoder]; [aCoder encodeObject:self.author forKey:kAuthor]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; self.author = [aDecoder decodeObjectForKey:kAuthor]; return self; } @end
在archive的action方法中加入Literature类对象,并进行归档:
// 创建Book子类对象 Literature *literature = [[Literature alloc] init]; literature.author = @"Shakespeare"; literature.name = book.name; literature.published = book.published; literature.price = book.price; literature.info = [[NSMutableArray alloc] initWithArray:[book.info copy]]; NSArray *array = [NSArray arrayWithObjects:str, date, number, book, literature, nil];
运行结果:

浙公网安备 33010602011771号