Foundation 框架 归档

时间:2021-01-31 17:37:36

一、使用XML属性列表归档

  此方法适用于NSString、NSDictionary、NSarray、NSDate、NSnumber,其中atomically参数表示先将字典写入临时备份文件,成功之后,把最终数据写入到dic指定的文件中

 #import <Foundation/Foundation.h>

 int main(int argc, const char * argv[])
{ @autoreleasepool {
//生成字典dic,并将字典dic写到xml文件myFirstDic文件
NSDictionary *dic = @{@"wukong": @"so smart", @"ranHanLu": @"so beautiful", @"family": @"best importtant!"};
if ([dic writeToFile: @"myFirstDic" atomically:YES] == NO) {
NSLog(@"Write to file failed");
} //读取
dic = [NSDictionary dictionaryWithContentsOfFile: @"myFirstDic"];
for (NSString *key in dic) {
NSLog(@"key is: %@, value is : %@", key, dic[key]);
}
}
return ;
}

二、适用NSKeyedUnarchiver类中得archiveRootObject:方法存储字典

  此方法可直接用于将NSString、NSDictionary、NSarray、NSDate、NSnumber归档,要适用于所有对象,需要对重写encodeWithCoder和initWithCoder方法,见三

 #import <Foundation/Foundation.h>

 int main(int argc, const char * argv[])
{ @autoreleasepool {
//适用NSKeyedUnarchiver类中得archiveRootObject:方法存储字典 NSDictionary *dic = @{
@"wukong": @"so smart", @"ranHanLu": @"so beautiful", @"archive": @"ending...."
};
[NSKeyedArchiver archiveRootObject: dic toFile: @"dic.archive"]; //读取
NSDictionary *new;
new = [NSKeyedUnarchiver unarchiveObjectWithFile: @"dic.archive"];
for (NSString *key in new) {
NSLog(@"key is: %@, value is : %@", key, new[key]);
} }
return ;
}

三、适用NSKeyedUnarchiver类中得archiveRootObject:方法,存储任意对象

  1.首先需要对自定义对象添加协议方法 1 #import <Foundation/Foundation.h>

 #import <Foundation/Foundation.h>

 @interface testClass: NSObject

 @property (copy, nonatomic) NSString *name, *address;
@end @implementation testClass
//添加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;
}
@synthesize name, address; @end
int main(int argc, const char * argv[])
{ @autoreleasepool {
testClass *myTest = [[testClass alloc] init]; myTest.name = @"wukong";
myTest.address = @"sichuan";
//归档
[NSKeyedArchiver archiveRootObject: myTest toFile: @"myTest.archive"];
//读出
myTest = [NSKeyedUnarchiver unarchiveObjectWithFile: @"myTest.archive"];
NSLog(@"Name is : %@, address is : %@", myTest.name, myTest.address); }
return ;
}

四、使用NSData自定义归档

  此示例将会使用到AddressBook, AddressCard, 以及 myTest类。

  以下为程序主体:

  

#import <Foundation/Foundation.h>
#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;
} @end int 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: @""];
[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 ;
}

  1.1 AddressCard类(interface)

 #import <Foundation/Foundation.h>

 @interface AddressCard : NSObject
@property (copy, nonatomic) NSString *firstName, *lastName, *email, *address, *phoneNumber;
-(void) setName: (NSString *) theName;
-(void) setEmail: (NSString *) theEmail;
-(void) setFirstName: (NSString *) theFirstName setLastName: (NSString *) theLastName setEmail: (NSString *) theEmail setAddress: (NSString *) theAddress setPhoneNumber: (NSString *) thePhoneNumber;
-(NSString *) name;
-(NSString *) email;
-(void) print;
-(BOOL) isEqual: (AddressCard *) theCard;
-(NSComparisonResult) compareName: (AddressCard *) theCard;
-(NSComparisonResult) check: (AddressCard *) theCard;
@end

  1.2 AddressCard类 (implementation)

 #import "AddressCard.h"

 @implementation AddressCard

 @synthesize firstName, lastName, email, phoneNumber, address;

 -(void) setFirstName: (NSString *) theFirstName setLastName: (NSString *)theLastName setEmail: (NSString *) theEmail setAddress: (NSString *) theAddress setPhoneNumber: (NSString *) thePhoneNumber
{
firstName = theFirstName;
lastName = theLastName;
email = theEmail;
address = theAddress;
phoneNumber = thePhoneNumber;
} -(void) print
{
NSLog(@"\n%@ %@ %@ %@ %@",firstName, lastName, email, address, phoneNumber);
} -(BOOL) isEqual: (AddressCard *) theCard
{
if ([firstName isEqualToString: theCard.firstName] && [email isEqualToString: theCard.email] && [lastName isEqualToString: theCard.lastName]) {
return YES;
}else{
return NO;
}
} -(NSComparisonResult) compareName: (AddressCard *) theCard
{
//return [name compare: theCard.name];
return [theCard.firstName compare: firstName];
} -(NSComparisonResult) check: (AddressCard *) theCard
{
return [theCard.lastName compare: lastName];
} -(void) encodeWithCoder: (NSCoder *) encoder
{
[encoder encodeObject: firstName forKey: @"addressCardFirstname"];
[encoder encodeObject: lastName forKey: @"addressCardLastname"];
[encoder encodeObject: email forKey: @"addressCardEmail"];
[encoder encodeObject: phoneNumber forKey: @"addressCardPhoneNumber"]; } -(id) initWithCoder: (NSCoder *) decoder
{
firstName = [decoder decodeObjectForKey:@"addressCardFirstname"];
lastName = [decoder decodeObjectForKey:@"addressCardLastname"];
email = [decoder decodeObjectForKey:@"addressCardEmail"];
phoneNumber = [decoder decodeObjectForKey:@"addressCardPhoneNumber"];
return self;
}
@end

  2.1 AddressBook类 (interface类)

 #import <Foundation/Foundation.h>
#import "AddressCard.h"
@interface AddressBook : NSObject
@property (copy, nonatomic) NSString *bookName;
@property (nonatomic, strong) NSMutableArray *book; -(instancetype) initWithName: (NSString *) name;
-(void) addAddressCard: (AddressCard *) theCard;
-(int) entries;
-(void) list;
-(AddressCard *) lookUp: (NSString *) name;
-(NSMutableArray *) lookUpAll: (NSString *) name;
-(void) removeCard: (AddressCard *) theCard;
-(void) sortByName;
-(NSArray *) sortBySelector;
-(BOOL) removeByLastName: (NSString *) lastName;
@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