一、使用XML属性列表归档
此方法适用于NSString、NSDictionary、NSarray、NSDate、NSnumber,其中atomically参数表示先将字典写入临时备份文件,成功之后,把最终数据写入到dic指定的文件中
1 #import2 3 int main(int argc, const char * argv[]) 4 { 5 6 @autoreleasepool { 7 //生成字典dic,并将字典dic写到xml文件myFirstDic文件 8 NSDictionary *dic = @{ @"wukong": @"so smart", @"ranHanLu": @"so beautiful", @"family": @"best importtant!"}; 9 if ([dic writeToFile: @"myFirstDic" atomically:YES] == NO) {10 NSLog(@"Write to file failed");11 }12 13 //读取14 dic = [NSDictionary dictionaryWithContentsOfFile: @"myFirstDic"];15 for (NSString *key in dic) {16 NSLog(@"key is: %@, value is : %@", key, dic[key]);17 }18 }19 return 0;20 }
二、适用NSKeyedUnarchiver类中得archiveRootObject:方法存储字典
此方法可直接用于将NSString、NSDictionary、NSarray、NSDate、NSnumber归档,要适用于所有对象,需要对重写encodeWithCoder和initWithCoder方法,见三
1 #import2 3 int main(int argc, const char * argv[]) 4 { 5 6 @autoreleasepool { 7 //适用NSKeyedUnarchiver类中得archiveRootObject:方法存储字典 8 9 NSDictionary *dic = @{10 @"wukong": @"so smart", @"ranHanLu": @"so beautiful", @"archive": @"ending...."11 };12 [NSKeyedArchiver archiveRootObject: dic toFile: @"dic.archive"];13 14 //读取15 NSDictionary *new;16 new = [NSKeyedUnarchiver unarchiveObjectWithFile: @"dic.archive"];17 for (NSString *key in new) {18 NSLog(@"key is: %@, value is : %@", key, new[key]);19 }20 21 }22 return 0;23 }
三、适用NSKeyedUnarchiver类中得archiveRootObject:方法,存储任意对象
1.首先需要对自定义对象添加协议方法 1 #import <Foundation/Foundation.h>
1 #import2 3 @interface testClass: NSObject 4 5 @property (copy, nonatomic) NSString *name, *address; 6 @end 7 8 @implementation testClass 9 //添加encodeWithCoder和initWithCoder方法10 -(void) encodeWithCoder: (NSCoder *) encoder11 {12 [encoder encodeObject: name forKey: @"testClassName"];13 [encoder encodeObject: address forKey: @"testClassAddress"];14 }15 16 -(id) initWithCoder: (NSCoder *) decoder17 {18 name = [decoder decodeObjectForKey: @"testClassName"];19 address = [decoder decodeObjectForKey: @"testClassAddress"];20 21 return self;22 }23 @synthesize name, address;24 25 @end26 int main(int argc, const char * argv[])27 {28 29 @autoreleasepool {30 testClass *myTest = [[testClass alloc] init];31 32 myTest.name = @"wukong";33 myTest.address = @"sichuan";34 //归档35 [NSKeyedArchiver archiveRootObject: myTest toFile: @"myTest.archive"];36 //读出37 myTest = [NSKeyedUnarchiver unarchiveObjectWithFile: @"myTest.archive"];38 NSLog(@"Name is : %@, address is : %@", myTest.name, myTest.address);39 40 }41 return 0;42 }
四、使用NSData自定义归档
此示例将会使用到AddressBook, AddressCard, 以及 myTest类。
以下为程序主体:
#import#import "AddressBook.h"#import "AddressCard.h"@interface testClass: NSObject@property (copy, nonatomic) NSString *name, *address;@end@implementation testClass@synthesize name, address;//添加encodeWithCoder和initWithCoder方法-(void) encodeWithCoder: (NSCoder *) encoder{ [encoder encodeObject: name forKey: @"testClassName"]; [encoder encodeObject: address forKey: @"testClassAddress"];}-(id) initWithCoder: (NSCoder *) decoder{ name = [decoder decodeObjectForKey: @"testClassName"]; address = [decoder decodeObjectForKey: @"testClassAddress"]; return self;}@endint main(int argc, const char * argv[]){ @autoreleasepool { //创建myTest实例 testClass *myTest = [[testClass alloc] init]; //创建myBook实例 AddressBook *mybook = [[AddressBook alloc] init]; //创建myCard实例 AddressCard *card1 = [[AddressCard alloc] init]; //创建NSMutableData实例,用于存放归档数据 NSMutableData *mutableData = [NSMutableData data]; //创建NSData用于读取归档数据 NSData *data = [NSData data]; //创建NSKeyedArchiver实例,并指定归档到mutableData NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData: mutableData]; //创建NSKeyedUnarchiver,用于读取归档数据 NSKeyedUnarchiver *unArchiver; myTest.name = @"wukong"; myTest.address = @"sichuan"; [card1 setFirstName: @"sun" setLastName:@"wukong" setEmail:@"999@163.com" setAddress: @"huaGuoShan" setPhoneNumber: @"9999999"]; [mybook addAddressCard: card1]; //存档对象 [archiver encodeObject: myTest forKey: @"MyTest"]; [archiver encodeObject: mybook forKey: @"MyBook"]; //表明存档结束 [archiver finishEncoding]; //将存档数据写入指定文件 if ([mutableData writeToFile: @"firstDataArchive" atomically:YES] == NO) { NSLog(@"\nArchive Failed"); } //从指定文件读取存档数据 data = [NSData dataWithContentsOfFile: @"firstDataArchive"]; //指定从data区解码 unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: data]; //解码开始 myTest = [unArchiver decodeObjectForKey: @"MyTest"]; mybook = [unArchiver decodeObjectForKey: @"MyBook"]; //显示 [mybook list]; } return 0;}
1.1 AddressCard类(interface)
1 #import2 3 @interface AddressCard : NSObject 4 @property (copy, nonatomic) NSString *firstName, *lastName, *email, *address, *phoneNumber; 5 -(void) setName: (NSString *) theName; 6 -(void) setEmail: (NSString *) theEmail; 7 -(void) setFirstName: (NSString *) theFirstName setLastName: (NSString *) theLastName setEmail: (NSString *) theEmail setAddress: (NSString *) theAddress setPhoneNumber: (NSString *) thePhoneNumber; 8 -(NSString *) name; 9 -(NSString *) email;10 -(void) print;11 -(BOOL) isEqual: (AddressCard *) theCard;12 -(NSComparisonResult) compareName: (AddressCard *) theCard;13 -(NSComparisonResult) check: (AddressCard *) theCard;14 @end
1.2 AddressCard类 (implementation)
1 #import "AddressCard.h" 2 3 @implementation AddressCard 4 5 @synthesize firstName, lastName, email, phoneNumber, address; 6 7 -(void) setFirstName: (NSString *) theFirstName setLastName: (NSString *)theLastName setEmail: (NSString *) theEmail setAddress: (NSString *) theAddress setPhoneNumber: (NSString *) thePhoneNumber 8 { 9 firstName = theFirstName;10 lastName = theLastName;11 email = theEmail;12 address = theAddress;13 phoneNumber = thePhoneNumber;14 }15 16 17 -(void) print18 {19 NSLog(@"\n%@ %@ %@ %@ %@",firstName, lastName, email, address, phoneNumber);20 }21 22 -(BOOL) isEqual: (AddressCard *) theCard23 {24 if ([firstName isEqualToString: theCard.firstName] && [email isEqualToString: theCard.email] && [lastName isEqualToString: theCard.lastName]) {25 return YES;26 }else{27 return NO;28 }29 }30 31 -(NSComparisonResult) compareName: (AddressCard *) theCard32 {33 //return [name compare: theCard.name];34 return [theCard.firstName compare: firstName];35 }36 37 -(NSComparisonResult) check: (AddressCard *) theCard38 {39 return [theCard.lastName compare: lastName];40 }41 42 -(void) encodeWithCoder: (NSCoder *) encoder43 {44 [encoder encodeObject: firstName forKey: @"addressCardFirstname"];45 [encoder encodeObject: lastName forKey: @"addressCardLastname"];46 [encoder encodeObject: email forKey: @"addressCardEmail"];47 [encoder encodeObject: phoneNumber forKey: @"addressCardPhoneNumber"];48 49 }50 51 -(id) initWithCoder: (NSCoder *) decoder52 {53 firstName = [decoder decodeObjectForKey:@"addressCardFirstname"];54 lastName = [decoder decodeObjectForKey:@"addressCardLastname"];55 email = [decoder decodeObjectForKey:@"addressCardEmail"];56 phoneNumber = [decoder decodeObjectForKey:@"addressCardPhoneNumber"];57 return self;58 }59 @end
2.1 AddressBook类 (interface类)
1 #import2 #import "AddressCard.h" 3 @interface AddressBook : NSObject 4 @property (copy, nonatomic) NSString *bookName; 5 @property (nonatomic, strong) NSMutableArray *book; 6 7 -(instancetype) initWithName: (NSString *) name; 8 -(void) addAddressCard: (AddressCard *) theCard; 9 -(int) entries;10 -(void) list;11 -(AddressCard *) lookUp: (NSString *) name;12 -(NSMutableArray *) lookUpAll: (NSString *) name;13 -(void) removeCard: (AddressCard *) theCard;14 -(void) sortByName;15 -(NSArray *) sortBySelector;16 -(BOOL) removeByLastName: (NSString *) lastName;17 @end
2.2 AddressBook类 (implementation)
#import "AddressBook.h"@implementation AddressBook@synthesize book, bookName;-(instancetype) initWithName: (NSString *) name{ self = [super init]; if (self) { bookName = [NSString stringWithString: name]; book = [NSMutableArray array]; } return self;}-(instancetype) init{ return [self initWithName: @"noName"];}-(void) addAddressCard: (AddressCard *) theCard{ [book addObject: theCard];}-(int) entries{ return (int)[book count];}-(void) list{ for (AddressCard *theCard in book) { [theCard print]; }}-(AddressCard *) lookUp: (NSString *) name{ NSUInteger result = [book indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { if ([[obj firstName] caseInsensitiveCompare: name] || [[obj lastName] caseInsensitiveCompare: name] || [[obj email] caseInsensitiveCompare:name] || [[obj phoneNumber] caseInsensitiveCompare: name]) { *stop = YES; return YES; }else{ return NO; } }]; if (result != NSNotFound) { return book[result]; }else{ return nil; } /*NSUInteger result = [book indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { if ([[obj name] caseInsensitiveCompare: name] == NSOrderedSame ) { *stop = YES; return YES; }else{ return NO; } }]; if (result != NSNotFound) { return book[result]; }else{ return nil; } */ /* for (AddressCard *theCard in book) { if ([theCard.name caseInsensitiveCompare: name] == NSOrderedSame) { return theCard; } } return Nil; */}//查看数组中得所有元素,并放到可变数组中返回-(NSMutableArray *) lookUpAll:(NSString *)name{ NSMutableArray *matchs = [NSMutableArray array]; NSIndexSet *all = [book indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { if ([[obj name] rangeOfString: name].location == NSNotFound) { [matchs addObject: obj]; return YES; }else{ return NO; } }]; if ([matchs count]) { return matchs; }else{ return nil; } /* NSMutableArray *matchs = [NSMutableArray array]; NSIndexSet *all = [book indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { if ([[obj name] compare: name] == NSOrderedSame) { [matchs addObject: obj]; return YES; }else{ return NO; } }]; if ([matchs count]) { return matchs; }else{ return nil; } */}-(void) removeCard: (AddressCard *) theCard{ [book removeObjectIdenticalTo: theCard]; }-(void) sortByName{// SEL s = @selector(compareName:);// [book sortUsingSelector: s]; [book sortUsingComparator:^(id obj1, id obj2) { return [[obj2 name] compare: [obj1 name]]; }];}-(NSArray *) sortBySelector{ return [book sortedArrayUsingSelector: @selector(check:)];}-(BOOL) removeByLastName: (NSString *) lastName{ NSUInteger result = [book indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { if ([[obj lastName] caseInsensitiveCompare: lastName] == NSOrderedSame) { [book removeObject: obj]; *stop = YES; return YES; }else{ return NO; } }]; if (result != NSNotFound) { return YES; }else{ return NO; }}-(void) encodeWithCoder: (NSCoder *) encoder{ [encoder encodeObject: book forKey: @"AddressBookBook"]; [encoder encodeObject: bookName forKey: @"AddressBookName"];}-(id) initWithCoder: (NSCoder *) decoder{ book = [decoder decodeObjectForKey: @"AddressBookBook"]; bookName = [decoder decodeObjectForKey: @"AddressBookName"]; return self;}@end