四种数据存储方式(上)

1.Plist  

读取:

if([NSFileManager defaultManager] fileExistsAtPath:filePath]){

   NSArray *array = [NSArray alloc] initWithContentsOfFile:filePath];

}

写入:

[array writeToFile:filePath atomically:YES];


2.归档

对应的类需要实现NSCoding,NSCopying

-(id)initWithCoder:(NSCoder *)aDecoder{

self = [super init];/self = [super initWithCoder:aDecoder];

if (self){ 

 foo = [aDecoder decodeObjectForKey:kFooKey];

someInt = [aDecoder decodeIntForKey:kSomeInKey];

someFloat = [aDecoder decodeFloatForKey:kAgeKey];

}  return self;}

-(void)encodeWithCoder:(NSCoder *)encoder{

//[super encodeWithCoder:encoder];

[encoder encodeObject:foo forKey:kFooKey];

[encoder encodeInt:someInt forKey:kSomeIntKey];

[encoder encodeFloat:someFloat forKey:kSomeFloat];}

简单归档:

BOOL success = [NSKeyedArchiverArchiveRootObject:object toFile:filePath];

简单解档:

object = [NSKeyedUnarchiver unarchiveObjectWithFile:homePath];

多对象归档

NSMutableData *data = [[NSMutableData alloc] init];

NSKeyArchiver *archiver = [[NSKeyArchiver alloc] initForWritingWithMutableData:data];

[archiver encodeObject:myObject forKey:@"keyValueString"];

[archiver encodeObject:object2 for:@"object2"];

[archiver finishEncoding];

BOOL success = [data writeToFile:@"data.archive" atomically:YES];

多对象解档:

NSData *data = [[NSMutableData alloc] initWithContentsOfFile:filePath];

NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]]initForReadingWithData:data];

object = [unarchiver decoderObjectForKey:kRootKey];

[unarchiver finisthDecoding];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容