归档也叫序列化,是将文件存在硬盘,解码是从硬盘还原
一、使用属性列表进行归档
如果对象是NSString,NSDictionary,NSArray,NSData,NSNumber,NSDate,可以是使用writeToFile:atomically方法将数据写到文件,注意这种方式是明文。
NSArray
*inputArray = [NSArray arrayWithObjects:@“abc”, @“123”,
@“qiaohaibin”];
//写入文件
当前目录下test.plist
//一般写入都是写入沙盒Documents下
BOOL result = [inputArray
writeToFile:@“test.plist”
atomically:YES];
if(!result){
NSLog(@“fail to write to
file”);
}
//读出文件
NSArray *outputArray = [NSArray
arrayWithContentsOfFile:@“test.plist”];
NSLog(@“%@“,
outputArray);
二、使用NSKeyedArchiver和NSkeyedUnarchiver进行归档和解档。
//文件完整路径
NSString
*filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [filePath
stringByAppendingPathComponent:@“test.archive"];
1.对上面所说的类和基本数据进行归档和解档
//归档
NSMutableData
*inputData = [NSMutableData data];
NSKeyedArchiver *archiver =
[[NSKeyedArchiver alloc]
initForWritingWithMutableData:inputData];
[archiver
encodeObject:[NSArray arrayWithObject:@“qiaohaibin”]
forKey:@“array”];
[archiver encodeInt:24
forKey:@“age”];
[archiver finishEncoding];
BOOL result =
[inputData writeToFile:fileName
atomically:YES];
if(!result){
NSLog(@“fail to archive to
file”);
}
//解档
NSData *outputData = [NSMutaleData
data];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]
initForReadingWithData:outputData];
NSArray *array = [unarchiver
decodeObjectForKey:@“array”];
int age = [unarchiver
decodeIntForKey:@“age”];
2.自定义对象进行归档和解档(需要事项NSCoding协议)
//归档时调用
-
(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeInt:_age
forKey:@“AGE”];
[aCoder encodeObject:_username
forKey:@“USERNAME”];
}
//解档时调用
- (id)initWithCoder:(NSCoder
*)aDecoder{
self.age = [aDecoder
decodeObjectForKey:@“AGE”];
self.username = [aDecoder
decodeObjectForKey:@“USERNAME”];
}
原文:http://www.cnblogs.com/dilin/p/3699588.html