您的位置:首页 > 其它

DataPersistence 文件管理

2015-09-01 20:44 330 查看
//沙盒机制:iOS系统会为每个app分配一个文件夹(sandbox),这个文件夹只允许当前应用访问

/*

//沙盒主目录

NSLog(@"%@", NSHomeDirectory());

//Documents,存一些比较重要的资料(文档),同步时会同步化此文件夹,此文件夹不能存过大的数据

[NSString stringWithFormat:@"%@/Documents", NSHomeDirectory()];//访问方式一

//访问方式二:

//搜索文件夹,并返回路径

//参数1:搜索的文件夹名字

//参数2.搜索的区域

//参数3.返回文件夹的路径是相对路径(NO,也就是有个波浪线在前面),还是绝对路径(YES,完整的路径)

NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *docPath = [array firstObject];

NSLog(@"Documents-------------%@", docPath);

//Library,

NSArray *libraryArray = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

NSString *lbString = [libraryArray firstObject];

NSLog(@"Library--------------------%@", lbString);

//Caches,缓存文件夹

NSArray *cachesArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

NSString *cachesString = [cachesArray firstObject];

NSLog(@"Caches------------------%@", cachesString);

//Preferences,配置文件夹,plist

//找不到

//tmp,临时文件夹,存放临时文件(比如:zip压缩包)

NSString *tmp = NSTemporaryDirectory();

NSLog(@"tmp--------%@", tmp);

//包,存放Xcode工程里的资源,包内资源是只读的

NSLog(@"%@", [[NSBundle mainBundle] bundlePath]);

//数据持久化的方式

//1.文件读写,简单的数据存储

//2.归档,复杂的数据存储

//3.NSUserDefaults,少量数据存储

//4.数据库,大量数据存储

//5.CoreData

//文件读写

//支持类型: NSString, NSArray, NSDictionary, NSData

*/

//NSString

//读内容:initWithContentsOfFile:encoding:error:

//写内容:writeToFile:atomically:encoding:error:

//NSArray

//读内容:initWithContentsOfFile:

//写内容:writeToFile:atomically:

//NSDictionary

//读内容:initWithContentsOfFile:

//写内容:writeToFile:atomically:

//NSData

//读内容:initWithContentsOfFile:

//写内容:writeToFile:atomically:

//内容展示

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];//docment的路径

NSString *filePath = [NSString stringWithFormat:@"%@/1.txt", docPath];//拼接一个路径

// NSLog(@"%@", filePath);

NSError *error = nil;

NSString *content = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];

if (error) {

NSLog(@"读文件失败:%@", error);

}else {

NSLog(@"读取成功");

self.label.text = content;

}

//NSArray写入

NSArray *array = @[@"爱妃", @"王妃", @"嫔妃"];

NSString *tempPath = NSTemporaryDirectory();

NSString *filePath1 = [NSString stringWithFormat:@"%@2.plist", tempPath];

// NSLog(@"%@", filePath1);

BOOL result = [array writeToFile:filePath1 atomically:YES];

if (result) {

NSLog(@"写入成功");

}else {

NSLog(@"写入失败");

}

//NSArray读写

NSArray *contentArray = [[NSArray alloc] initWithContentsOfFile:filePath1];

NSLog(@"%@", contentArray);

//NSDictionary的读写

//写到Caches文件下的3.plist中

//并从中读取内容

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"name", @"yangchao", @"age", @"21", nil];

NSArray *cachesArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

NSString *cachesString = [cachesArray firstObject];

NSString *filePath2 = [NSString stringWithFormat:@"%@3.plist", cachesString];

BOOL result1 = [dic writeToFile:filePath2 atomically:YES];

if (result1) {

NSLog(@"写入成功");

}else {

NSLog(@"写入失败");

}

//NSDictionary的读取

NSDictionary *dic1 = [[NSDictionary alloc] initWithContentsOfFile:filePath2];

NSLog(@"%@",dic1);

//NSData

NSData *data = [@"fuckyou" dataUsingEncoding:NSUTF8StringEncoding];

//把data数据写入Library文件下的4.txt

NSArray *libraryArray = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

NSString *lbString = [libraryArray firstObject];

NSString *filePath3 = [NSString stringWithFormat:@"%@4.txt", lbString];

BOOL result2 = [data writeToFile:filePath3 atomically:YES];

if (result2) {

NSLog(@"写入成功");

}else {

NSLog(@"写入失败");

}

//从文件中读取内容

NSData *data1 = [[NSData alloc] initWithContentsOfFile:filePath3];

NSLog(@"%@", data1);

//归档,用于对自定义类型(比如Girl)的数据进行数据持久化

//实质,把自定义类(Girl)转化成NSData类型,在对NSData数据进行存储

//前提,支持归档的类,必须遵守NSCoding协议

Girl *girl = [[Girl alloc] init];

girl.name = @"爱妃";

girl.gender = @"女";

girl.age = @"18";

//girl->NSData

//NSKeyedArchiver,继承于NSCoder,工具类,把数据转化NSData类型

NSMutableData *mData =[[NSMutableData alloc] initWithCapacity:0];

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

//把girl对象压入Data中,需要指定其key值,方便从中提取

[archiver encodeObject:girl forKey:@"GF"];

//停止

[archiver finishEncoding];

NSLog(@"%@",mData);

NSString *filePath4 = [NSString stringWithFormat:@"%@girl.plist", tempPath];

NSLog(@"%@", filePath4);

result = [mData writeToFile:filePath4 atomically:YES];

if (result) {

NSLog(@"归档成功");

}else {

NSLog(@"归档失败");

}

//反归档

NSData *data10 = [[[NSData alloc] initWithContentsOfFile:filePath4] autorelease];

//解压工具

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

Girl *girl1 = [unarchiver decodeObjectForKey:@"GF"];

[unarchiver finishDecoding];

[unarchiver release];

NSLog(@"%@", girl1);

//NSUserDefaults,继承于NSObject,系统提供的轻量级数据持久化类,绑定了一个plist文件

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

//存数据

[defaults setBool:YES forKey:@"isGirl"];

[defaults setInteger:1314 forKey:@"time"];

[defaults setFloat:59.99 forKey:@"score"];

[defaults setObject:@"张三" forKey:@"name"];

//立刻存入

[defaults synchronize];//同步存入

//取数据

BOOL isGirl = [defaults boolForKey:@"isGirl"];

NSLog(@"%d", isGirl);

NSInteger time = [defaults integerForKey:@"time"];

NSLog(@"%ld", time);

float score = [defaults floatForKey:@"score"];

NSLog(@"%.2f", score);

NSString *name = [defaults objectForKey:@"name"];

NSLog(@"%@", name);

//如何识别你的应用是第一次打开

if (![defaults boolForKey:@"isFirst"]) {

NSLog(@"第一次");

[defaults setBool:YES forKey:@"isFirst"];

}else {

NSLog(@"不是第一次");

}

//NSFileManager,继承于NSObject,文件管理类

NSFileManager *fm = [NSFileManager defaultManager];

//搜索文件并返回路径,路径都是绝度路径

NSArray *paths = [fm URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];

NSLog(@"%@", paths);

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

- (void)dealloc {

[_label release];

[_textField release];

[super dealloc];

}

- (IBAction)press:(UIButton *)sender {

//保存数据(向文件内写数据)

//把内容写到docment文件夹的某个文件中

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];//docment的路径

NSString *filePath = [NSString stringWithFormat:@"%@/1.txt", docPath];//拼接一个路径

// NSLog(@"%@", filePath);

NSError *error = nil;

BOOL result = [self.textField.text writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

if (result) {

NSLog(@"写入成功");

}else{

NSLog(@"写入失败:%@", error);

}

self.label.text = self.textField.text;

}

//创建文件夹

- (IBAction)creat:(UIButton *)sender {

//1.创建文件夹管理类

NSFileManager *fm = [NSFileManager defaultManager];

//文件夹路径

NSString *string = [NSString stringWithFormat:@"%@/heigege", NSHomeDirectory()];

NSLog(@"%@", string);

//2.创建文件夹

NSError *error = nil;

BOOL result = [fm createDirectoryAtPath:string withIntermediateDirectories:YES attributes:nil error:&error];

//判断是否成功

if (result) {

NSLog(@"创建成功");

}else {

NSLog(@"创建失败");

}

}

//移动

- (IBAction)move:(UIButton *)sender {

NSFileManager *fm = [NSFileManager defaultManager];

NSString *sourcePath = [NSString stringWithFormat:@"%@/heigege", NSHomeDirectory()];

NSString *destinationPath = [NSString stringWithFormat:@"%@/heigege", NSTemporaryDirectory()];

// NSLog(@"%@", destinationPath);

NSError *error = nil;

BOOL result = [fm moveItemAtPath:sourcePath toPath:destinationPath error:&error];

if (result) {

NSLog(@"移动成功");

}else {

NSLog(@"移动失败");

}

}

//复制

- (IBAction)copy:(UIButton *)sender {

NSFileManager *fm = [NSFileManager defaultManager];

NSString *sourcePath = [NSString stringWithFormat:@"%@/heigege", NSHomeDirectory()];

NSArray *libraryArray = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

NSString *lbString = [libraryArray firstObject];

NSString *libraryPath = [NSString stringWithFormat:@"%@/heigege", lbString];

NSError *error = nil;

BOOL result = [fm copyItemAtPath:sourcePath toPath:libraryPath error:&error];

if (result) {

NSLog(@"复制成功");

}else {

NSLog(@"复制失败:%@", error);

}

}

//删除

- (IBAction)delete:(UIButton *)sender {

NSFileManager *fm = [NSFileManager defaultManager];

NSString *destinationPath = [NSString stringWithFormat:@"%@/heigege", NSTemporaryDirectory()];

// NSLog(@"%@", destinationPath);

NSError *error = nil;

BOOL result = [fm removeItemAtPath:destinationPath error:&error];

if (result) {

NSLog(@"删除成功");

}else {

NSLog(@"删除失败:%@", error);

}

}

在这里我们需要创建一个girl类,具体内容如下

@implementation Girl

- (void)dealloc

{

self.name = nil;

self.age = nil;

self.gender = nil;

[super dealloc];

}

- (NSString *)description {

return [NSString stringWithFormat:@"name:%@ age:%@ gender:%@", _name, _age, _gender];

}

#pragma mark - NSCoding

//编码(写入)

- (void)encodeWithCoder:(NSCoder *)aCoder {

//编码的key值必须和解码时的key值保持一致

[aCoder encodeObject:self.name forKey:@"name"];

[aCoder encodeObject:self.age forKey:@"age"];

[aCoder encodeObject:self.gender forKey:@"gender"];

}

//解码(读取)

- (id)initWithCoder:(NSCoder *)aDecoder {

if (self = [super init]) {

self.name = [aDecoder decodeObjectForKey:@"name"];

self.age = [aDecoder decodeObjectForKey:@"age"];

self.gender = [aDecoder decodeObjectForKey:@"gender"];

}

return self;

}

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