
在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 总结 以上是内存溢出为你收集整理的文件加载和保存全部内容,希望文章能够帮你解决文件加载和保存所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)