初级数据持久化(沙盒三个文件的路径的获取、简单与复杂对象的读写、NSUserDefaults、NSFileManager )
NSDocumentDirectory 是指程序中对应的Documents路径,而NSDocumentionDirectory对应于程序中的Library/Documentation路径,这个路径是没有读写权限的,所以看不到文件生成。
IOS开发是在沙盒中开发的,对一些部分的文件的读写进行了限制,只能在几个目录下读写文件:
(1)Documents:应用中用户数据可以放在这里,iTunes备份和恢复的时候会包括此目录
(2)tmp:存放临时文件,iTunes不会备份和恢复此目录,此目录下文件可能会在应用退出后删除
(3)Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除
对于文件操作,NSSearchPathForDirectoriesInDomains是核心函数。
ViewController.m
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@property(nonatomic,strong)UIImageView * imV;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 沙盒 就是一个文件夹
// *********获取沙盒路径************
/*
// 获取用户名
NSString * s = NSUserName();
// 获取主路径
NSString * rootPath = NSHomeDirectoryForUser(s);
NSLog(@"%@",rootPath);
*/
// ************获取沙盒三个文件夹的路径***********
/*
// other
NSString * rootPath1 = NSHomeDirectory();
NSLog(@"rootPath1 = %@",rootPath1);
// 获取doucments路径
// 作用 数据运行程序后产生,主要存储数据库等不常改变的数据文件。存在这里的文件会被备份。(下载的文件不能放在这里,如果放在这上传APPStore的时候会被拒掉)
NSString * documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSLog(@"documentsPath = %@",documentsPath);
// 获取Caches路径
// 作用存放缓存文件,例如:音频、视频、图片(不会被自动备份)
NSString * cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSLog(@"cachesPath = %@",cachesPath);
// 获取tmp路径
// 作用:存放临时文件,程序下次启动不需要,退出清空。
NSString * tmpPath = NSTemporaryDirectory();
NSLog(@"tmpPath = %@",tmpPath);
*/
//***********简单文件的写入*****************
/*
//准备路径
NSString * documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSLog(@"%@",documentsPath);
//----------------NSString的写和读---------------
//NSString NSArray NSDictionary NSData
NSString * str1 = @"hello world";
NSString * filePath = [documentsPath stringByAppendingString:@"/hello.txt"];
//写入
// [str1 writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
//读出
NSString *s1 = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"s1 = %@" ,s1);
//------------- NSArray 的写和读 --------------
//stringByAppendingPathComponent: 路径不需要写斜线,不需要写后缀
NSString * filePath2 = [documentsPath stringByAppendingPathComponent:@"array"];
NSArray *array1 = @[@"1",@"2",@"3"];
//写入
// [array1 writeToFile:filePath2 atomically:YES];
//读
NSArray * array2 = [NSArray arrayWithContentsOfFile:filePath2];
// NSLog(@"array2 = %@",array2);
//------------- NSDictionary 的写和读------------
NSString * filePath3 = [documentsPath stringByAppendingPathComponent:@"Dictionary"];
//写入
NSDictionary * dict = @{@"山西":@"太原",@"河北":@"石家庄"};
[dict writeToFile:filePath3 atomically:YES];
//读
NSDictionary * dict2 = [NSDictionary dictionaryWithContentsOfFile:filePath3];
NSLog(@"dict2 %@",dict2);
//遍历字典
for (id obj in dict2) {
NSLog(@"dict2 %@ = %@",obj,[dict2 valueForKey:obj]);
}
*/
//*************** 复杂对象写入1 *****************
/*
//创建对象
Person * p1 = [[Person alloc]init];
p1.name = @"贝爷";
p1.age = 20;
//准备NSMutableData 存数据
NSMutableData * data = [NSMutableData data];
创建归档工具
NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
//开始归档
[archiver encodeObject:p1 forKey:@"p1"];
//完成归档
[archiver finishEncoding];
//准备路径
NSString * documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString * filePath4 = [documentsPath stringByAppendingPathComponent:@"贝爷.m"];
NSLog(@"%@",documentsPath);
//data写入
// [data writeToFile:filePath4 atomically:YES];
//读
NSData * data1 = [NSData dataWithContentsOfFile:filePath4];
NSLog(@"data1 = %@",data1);
//反归档
NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data1];
//转换成对象
Person * p2 = [unarchiver decodeObjectForKey:@"p1"];
//反归档完成
[unarchiver finishDecoding];
NSLog(@"%@ == %ld",p2.name,p2.age);
*/
//*************** 复杂对象写入2 *****************
/*
//准备路径
NSString * documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
//拼接路径
NSString * filePath5 = [documentsPath stringByAppendingPathComponent:@"person.mp4"];
//创建person对象
Person *p3 = [[Person alloc]init];
p3.name = @"六娃";
p3.age = 18;
//存
// [NSKeyedArchiver archiveRootObject:p3 toFile:filePath5];
//取 (这种归档方式,只能针对一个对象)
Person * p4 = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath5];
NSLog(@"%@ == %ld",p4.name,p4.age);
*/
//************* NSUserDefaults 通常用来写引导页 ********
/*
// 创建对象
NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
// 存
[ud setObject:@"yan3" forKey:@"lanou"];
// 同步数据
[ud synchronize];
// 取
NSLog(@"%@",[ud objectForKey:@"lanou"]);
*/
//************** 导航页测试 ****************
/*
// 创建对象
// NSUserDefaults 存一些简单的数据
NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
NSString *s = [ud objectForKey:@"first"];
if (s == nil) {
self.imV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"000.png"]];
self.imV.frame = self.view.bounds;
[self.view addSubview:_imV];
[ud setObject:@"NO" forKey:@"first"];
}
*/
//*********** NSFileManager 文件管理对象 ************
//路径
NSString * cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSLog(@"%@",cachesPath);
//创建文件管理对象
NSFileManager * fm = [NSFileManager defaultManager];
//创建文件夹
[fm createDirectoryAtPath:[cachesPath stringByAppendingPathComponent:@"00/test"] withIntermediateDirectories:YES attributes:nil error:nil];
//更改文件名
[fm moveItemAtPath:[cachesPath stringByAppendingPathComponent:@"00/test"] toPath:[cachesPath stringByAppendingPathComponent:@"Demo"] error:nil];
//移动文件位置
[fm moveItemAtPath:[cachesPath stringByAppendingPathComponent:@"00/test"] toPath:[cachesPath stringByAppendingPathComponent:@"Demo/test"] error:nil];
//删除文件
[fm removeItemAtPath:[cachesPath stringByAppendingPathComponent:@"Demo/test"] error:nil];
//判断一个文件是否存在
BOOL i = [fm fileExistsAtPath:@"Demo"];
NSLog(@"%d",i);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
Person.h
#import <Foundation/Foundation.h>
//一个类是否可以被归档反归档,要看是否遵循NSCoding协议。
@interface Person : NSObject<NSCoding>
@property(nonatomic,copy)NSString * name;
@property(nonatomic,assign)NSInteger age;
@end
Person.m
#import "Person.h"
@implementation Person
// 编码
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"p_name"];
[aCoder encodeInteger:self.age forKey:@"p_age"];
}
// 反编码
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"p_name"];
self.age = [aDecoder decodeIntegerForKey:@"p_age"];
}
return self;
}
@end