什么是归档?
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
NSString *filePath=[self dataFilePath];
NSLog(@"path:%@",filePath);
// 将数据归档到NSDictionary或NSMutableDictionary
NSMutableDictionary *dataDictionary=[[NSMutableDictionary alloc] init];
[dataDictionary setObject:@"My name is Tom" forKey:@"Tom"];
[dataDictionary setObject:@"My name is LiLei" forKey:@"LiLei"];
[dataDictionary setObject:@"My name is HanMeimei" forKey:@"HanMeimei"];
NSString *dictionaryName= [filePath stringByAppendingPathComponent:@"NSMutableDictionary"];
[dataDictionary writeToFile: dictionaryName atomically: YES];
// // 将数据归档到NSArray或NSMutableArray
NSMutableArray *dataArray=[[NSMutableArray alloc] init];
[dataArray addObject:@"Tom"];
[dataArray addObject:@"LiLei"];
[dataArray addObject:@"HanMeimei"];
NSNumber *number=[[NSNumber alloc] initWithInt:100];
[dataArray addObject:number];
NSString *arrayName= [filePath stringByAppendingPathComponent:@"NSMutableArray"];
[dataArray writeToFile: arrayName atomically: YES];
// 从文件中读取数据到NSDictionary或NSMutableDictionary中
NSMutableDictionary *newDictionary=[NSMutableDictionarydictionaryWithContentsOfFile:dictionaryName];
// 从文件中读取数据到NSArray或NSMutableArray中
NSMutableArray *newArray=[NSMutableArray arrayWithContentsOfFile:arrayName];
for (NSString *theStr in newDictionary) {
NSLog(@"----%@",theStr);
}
for (NSString *theStr in newArray) {
NSLog(@"----%@",theStr);
}
// NSKeyedArchiver 将数据归档到NSDictionary或NSMutableDictionary
NSString *dictionaryName= [filePath stringByAppendingPathComponent:@"ArchiverDictionary.archiver"];
[NSKeyedArchiver archiveRootObject:dataDictionary toFile:dictionaryName];
// NSKeyedArchiver 将数据归档到NSArray或NSMutableArray
NSString *arrayName= [filePath stringByAppendingPathComponent:@"ArchiverArray.archiver"];
[NSKeyedArchiver archiveRootObject:dataArray toFile:arrayName];
// NSKeyedUnarchiver
NSMutableDictionary *newDictionary=[NSKeyedUnarchiverunarchiveObjectWithFile:dictionaryName];
NSMutableArray *newArray=[NSKeyedUnarchiver unarchiveObjectWithFile:arrayName];
NSMutableArray *objArray=[NSMutableArray arrayWithObjects:
card1,
card2,
card3,
card4,
nil];
NSString *arrayName=[filePath stringByAppendingPathComponent:@"ObjectFile"];
BOOL isSuccess= [objArray writeToFile:arrayName atomically:YES];
if (isSuccess) {
NSLog(@"Success");
}else{
NSLog(@"False");
}
isSuccess= [NSKeyedArchiver archiveRootObject:objArray toFile:arrayName];
if (isSuccess) {
NSLog(@"Success");
}else{
NSLog(@"False");
}
'NSInvalidArgumentException', reason: '-[AddressCard encodeWithCoder:]: unrecognized selector sent to instance 0x1188ef60'