您的位置:首页 > 移动开发 > IOS开发

iOS之数据持久化 - 归档与反归档

2015-10-08 16:44 417 查看
转载 http://blog.csdn.net/liulala16/article/details/8281254
数据持久化,实际上就是将数据存放到网络或者硬盘上,这里是存储到本地的硬盘上,应用程序的本地硬盘是沙盒,沙盒实际上就是一个文件夹,它下面有4个文件夹。分别是Documents,Library,APP包和tmp文件夹,Documents里面主要是存储用户长期使用的文件,Library里面又有Caches和Preferences文件夹,Caches里面存放的是临时的文件,缓存。Preferences里面存放的是偏好设置。tmp里面也是临时的文件,不过和Caches还有区别,APP包里面是编译后的一些文件,包不能修改。

先创建一个Person类,定义3个属性

.h文件

#import<Foundation/Foundation.h>

@interface Person :NSObject<NSCoding>
{

NSString *name;

int age;

NSString *phone;
}
@property(nonatomic,retain)NSString
*name, *phone;
@property(nonatomic,assign)int age;
-(id)initWithName:(NSString *)aName phone:(NSString *)aPhone age:(int)aAge;//初始化方法

@end

.m文件

#import"Person.h"

@implementation Person
@synthesize name,age,phone;

-(id)initWithName:(NSString *)aName phone:(NSString *)aPhone age:(int)aAge
{
[superinit];

if (self) {

self.name = aName;

self.phone = aPhone;

self.age = aAge;
}
return
self;

}
- (void)encodeWithCoder:(NSCoder *)aCoder //将属性进行编码
{
[aCoder
encodeObject:self.nameforKey:@"name"];
[aCoder
encodeObject:self.phoneforKey:@"phone"];
[aCoderencodeInteger:self.ageforKey:@"age"];

}
- (id)initWithCoder:(NSCoder *)aDecoder //将属性进行解码
{

NSString *name1 = [aDecoder decodeObjectForKey:@"name"];

NSString *phone1 = [aDecoder decodeObjectForKey:@"phone"];

int age1 = [aDecoder decodeIntegerForKey:@"age"];

[selfinitWithName:name1
phone:phone1 age:age1];

return
self;

}

@end

主程序中进行归档与反归档

- (void)loadView

{

self.view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];

self.view.backgroundColor = [UIColor whiteColor];

Person *p1 = [[Person alloc]initWithName:@"jim" phone:@"654789" age:3];

Person *p2 = [[Person alloc]initWithName:@"tom" phone:@"5464" age:4];

//文件的归档

NSMutableData *data = [NSMutableData data ];

//创建一个归档类

NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];

[archiver encodeObject:p1 forKey:@"Person1"];

[archiver encodeObject:p2 forKey:@"Person2"];

[archiver finishEncoding];

[archiver release];

//将数据写入文件里

[data writeToFile:[self filePath] atomically:YES];

//反归档,从文件中取出数据

NSMutableData *data1 = [NSMutableData dataWithContentsOfFile:[self filePath]];

NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data1];

Person *p3 = [unarchiver decodeObjectForKey:@"Person1"];

Person *p4 = [unarchiver decodeObjectForKey:@"Person2"];

NSLog(@"%@ %@ %d",p3.name,p3.phone,p3.age);

NSLog(@"%@ %@ %d",p4.name,p4.phone,p4.age);

}

-(NSString *)filePath

{

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES)objectAtIndex:0];

NSString *path = [docPath stringByAppendingPathComponent:@"texts"];

// NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/texts"]; //两种方法都可以

return path;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: