美文网首页
四种数据存储方式(上)

四种数据存储方式(上)

作者: 凯旋之歌 | 来源:发表于2017-04-07 16:34 被阅读0次

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];

相关文章

网友评论

      本文标题:四种数据存储方式(上)

      本文链接:https://www.haomeiwen.com/subject/bmshattx.html