博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Foundation 框架 归档
阅读量:6333 次
发布时间:2019-06-22

本文共 12296 字,大约阅读时间需要 40 分钟。

一、使用XML属性列表归档

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

1 #import 
2 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 #import 
2 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 #import 
2 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 #import 
2 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 #import 
2 #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

  

 

转载于:https://www.cnblogs.com/pretty-guy/p/3958366.html

你可能感兴趣的文章
陈松松:视频营销成交率低,这三个因素没到位
查看>>
vmware nat模式原理探究,实现虚拟机跨网段管理
查看>>
JavaSE 学习参考:集合运算
查看>>
【Signals and Systems】 SYLLABUS
查看>>
RH135-2-command-line-interface
查看>>
浅谈OS
查看>>
mac下开启docker API远程调用
查看>>
tar 命令的详解
查看>>
Cisco路由器安全配置
查看>>
第十次作业
查看>>
给定一个字符串s,返回去掉子串"mi"后的字符串。
查看>>
Nginx 外的另一选择,轻量级开源 Web 服务器 Tengine 发布新版本
查看>>
Wrod中超链接的一些技巧
查看>>
我的友情链接
查看>>
IP_VFR-4-FRAG_TABLE_OVERFLOW【cisco设备报错】碎片***
查看>>
Codeforces Round #256 (Div. 2) D. Multiplication Table 【二分】
查看>>
ARM汇编指令格式
查看>>
HDU-2044-一只小蜜蜂
查看>>
HDU-1394-Minimum Inversion Number
查看>>
df -h 卡住
查看>>