Foundation 框架 归档
一、使用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
Foundation 框架 归档的更多相关文章
- Foundation框架下的常用类:NSNumber、NSDate、NSCalendar、NSDateFormatter、NSNull、NSKeyedArchiver
========================== Foundation框架下的常用类 ========================== 一.[NSNumber] [注]像int.float.c ...
- iOS开发系列—Objective-C之Foundation框架
概述 我们前面的章节中就一直新建Cocoa Class,那么Cocoa到底是什么,它和我们前面以及后面要讲的内容到底有什么关系呢?Objective-C开发中经常用到NSObject,那么这个对象到底 ...
- Foundation框架-NSString和NSMutableString
可变与不可变的字符串 --1-- Foundation框架介绍 1.1 框架介绍 --2-- NSString 2.1 NSString介绍及使用 2.2 NSString创建方式 2.3 从文件中 ...
- 08OC之Foundation框架
1.Foundation框架简述 在前面,我们创建一个类的时候,都会选择Cocoa Class.到底Cocoa Class是什么东西呢? Cocoa 不是一门编程语言,因为它可以运行在多种编程语言上, ...
- iOS - OC Foundation 框架
前言 框架是由许多类.方法.函数和文档按照一定的逻辑组织起来的集合,以使研发程序更容易. Foundation 框架:为所有程序开发奠定基础的框架称为 Foundation 框架. Cocoa :是指 ...
- iOS - Swift Foundation 框架
前言 框架是由许多类.方法.函数和文档按照一定的逻辑组织起来的集合,以使研发程序更容易. Foundation 框架:为所有程序开发奠定基础的框架称为 Foundation 框架. Cocoa :是指 ...
- iOS Foundation 框架概述文档:常量、数据类型、框架、函数、公布声明
iOS Foundation 框架概述文档:常量.数据类型.框架.函数.公布声明 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业 ...
- OC中Foundation框架
框架的概念 框架是由许多类.方法.函数.文档按照一定的逻辑组织起来的组合,以便使研发程序变的更容易在OS X下地Mac操作系统中大约有80个框架为所有程序开发奠定基础的框架称为Foundation框架 ...
- 79、iOS 的Cocoa框架、Foundation框架以及UIKit框架
Cocoa框架是iOS应用程序的基础 1. Cocoa是什么? Cocoa是 OS X和ios 操作系统的程序的运行环境. 是什么因素使一个程序成为Cocoa程序呢?不是编程语言,因为在Cocoa开发 ...
随机推荐
- Android消息机制不完全解析(下)
接着上一篇文章Android消息机制不完全解析(上),接着看C++部分的实现. 首先,看看在/frameworks/base/core/jni/android_os_MessageQueue.cpp文 ...
- 杭电 1272 POJ 1308 小希的迷宫
这道题是我学了并查集过后做的第三个题,教我们的学姐说这是并查集的基础题,所以有必要牢牢掌握. 下面就我做这道题的经验,给大家一些建议吧!当然,我的建议不是最好的,还请各位大神指出我的错误来,我也好改正 ...
- JAVA基础 (二)反射 深入解析反射机制
在谈论到反射这个问题时,你是否有例如以下疑问? 不管是在.NET还是Java中反射的原理和机制是一样的,理解了一种还有一种就能够迎刃而解,想要理解反射首先须要了解底层的一些概念和执行.理解了反射有助于 ...
- 初探swift语言的学习笔记(闭包 - 匿名函数或block块代码)
很多高级语言都支持匿名函数操作,在OC中的block也为大家所熟悉,然面在swift里好像是被重新作了一个定义,不叫匿名函数,或 block了,而叫闭包(closure).下面配合代码来理解一下swi ...
- English - consist of 和 compose of 的区别
comprise,compose,consist,constitute,include 这一组动词都有"组成,包含"的意思. comprise v.包含,包括,由……组成(整体): ...
- UpdatePanel + 弹出框
ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", "alert('操作成功!') ...
- events模块
/** * Created by Administrator on 2016/8/3. */ var http = require("http"); //Node 导入文件系统模块 ...
- R与数据分析旧笔记(六)多元线性分析 下
逐步回归 向前引入法:从一元回归开始,逐步加快变量,使指标值达到最优为止 向后剔除法:从全变量回归方程开始,逐步删去某个变量,使指标值达到最优为止 逐步筛选法:综合上述两种方法 多元线性回归的核心问题 ...
- 四轴飞行器1.6 emwin与ucgui的移植,汉字外挂字库移植和DEMO效果对比
飞控的遥控器打算自己做,这样全局都能掌握,可以通过遥控器对飞控的参数和飞行模式进行修改,而买遥控器是做不到这样的哈..以后做图传的时候,屏幕还可以实时现实摄像头拍回来的画面,挺好的哈.. 做遥控我们选 ...
- MySQL 分区表各个分区的行数
分区的信息是记录在information_schema.partitions 这个表里的.它不能直接定位行所在的分区,但它可查到每个分区中有多少行. 例子: select partition_name ...