四种数据存储方式(上)

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

你可能感兴趣的:(四种数据存储方式(上))