1、使用属性列表保存对象:
在Cocoa中,与一类名为属性列表的对象,常简称为plist。这些列表包含Cocoa知道如何操作的一组对象。具体来讲,Cocoa知道如何将它们保存到文件中并进行加载。属性列表类包括:NSArray,NSDictionary,NSString和NSData,以及它们的变体(Mutable)
eg:
2、编码对象
遗憾的是,无法总是将对象信息表示为属性列表类。如果能将所有对象都表示为数组字典,我们就没有必要使用自己的类了。所幸,Cocoa具备一种机制来将对象自身转化为某种格式并保存到磁盘中。对象可以将它们的实例变量和其它数据编码为数据块,然后保存到磁盘中。遗憾将这些数据块读到内存中,并且还能基于保存的数据创建新对象。这个过程称为编码和解码,或称为序列化和反序列化。
通过NSCoding协议,可以使用自己的对象实现相同功能,实现它的两个方法:
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
NSCoder是一个抽象类,定义一些有用的方法来在对象与NSData之间来回转换。完全不需要创建新NSCoder,因为它事件上并无多大作用。但是我们实际上要使用NSCoder的一些具体子类来编码和解码对象。我们将使用其中两个子类NSKeyedArchiver和NSKeyedUnArchiver.
下面是一个例子:
头文件类BookObj.h的源码:
在Cocoa中,与一类名为属性列表的对象,常简称为plist。这些列表包含Cocoa知道如何操作的一组对象。具体来讲,Cocoa知道如何将它们保存到文件中并进行加载。属性列表类包括:NSArray,NSDictionary,NSString和NSData,以及它们的变体(Mutable)
eg:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *array = [NSArray arrayWithObjects:@"First",
@"second",@"third",@"fourth",@"fifth",nil];
[array writeToFile:@"array.plist" atomically:YES];
2、编码对象
遗憾的是,无法总是将对象信息表示为属性列表类。如果能将所有对象都表示为数组字典,我们就没有必要使用自己的类了。所幸,Cocoa具备一种机制来将对象自身转化为某种格式并保存到磁盘中。对象可以将它们的实例变量和其它数据编码为数据块,然后保存到磁盘中。遗憾将这些数据块读到内存中,并且还能基于保存的数据创建新对象。这个过程称为编码和解码,或称为序列化和反序列化。
通过NSCoding协议,可以使用自己的对象实现相同功能,实现它的两个方法:
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
NSCoder是一个抽象类,定义一些有用的方法来在对象与NSData之间来回转换。完全不需要创建新NSCoder,因为它事件上并无多大作用。但是我们实际上要使用NSCoder的一些具体子类来编码和解码对象。我们将使用其中两个子类NSKeyedArchiver和NSKeyedUnArchiver.
下面是一个例子:
头文件类BookObj.h的源码:
//
// BookObj.h
//
#import <Cocoa/Cocoa.h>
@interface BookObj:NSObject<NSCoding>{
NSString *bookName;
NSString *author;
}
@property (copy) NSString *bookName;
@property (copy) NSString *author;
-(id)initWithName:(NSString *)name
author:(NSString *) au ;
@end
实现类BookObj.m的源码:
//
// BookObj.m
//
#import "BookObj.h"
@implementation BookObj
@synthesize bookName;
@synthesize author;
-(id)initWithName:(NSString *)name
author:(NSString *) au{
if (self = [super init]) {
self.bookName = name;
self.author = au;
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.bookName forKey:@"bookName"];
[aCoder encodeObject:self.author forKey:@"author"];
}
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self =[super init]) {
self.bookName = [aDecoder decodeObjectForKey:@"bookName"];
self.author = [aDecoder decodeObjectForKey:@"author"];
}
return self;
}
int main(int argc ,const char *argv[]){
BookObj *bookObj = [[BookObj alloc] initWithName:@"iPhone编程指南"
author:@"David"];
[NSKeyedArchiver archiveRootObject:bookObj toFile:@"bookObj.plist"];
NSLog(@"Success to archive file bookObj.plist!");
BookObj *bookOb = [NSKeyedUnarchiver unarchiveObjectWithFile:@"bookObj.plist"];
NSLog(@"The book name is :%@",bookOb.author);
return 0;
}
@end