沙盒机制:iOS应用程序只能在该程序创建的应用目录下读取文件。
每个沙盒包括三个文件夹:Documents、Library、tmp
Documents:能备份,永久存储,iTunes备份和恢复的时候会包括此目录
Library:不能备份,不能永久存储,
tmp 不能备份,但永久存储,用于存放临时文件
一:获取Documents目录路径
NSArray *arr=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
for (NSString *path in arr) {
NSLog(@"path is %@",path);
}
二:创建一个文件夹
NSString *dirPath=arr[0];
//stringByAppendingPathComponent:会在text前加一个/
dirPath =[dirPath stringByAppendingPathComponent:@"text"];
//此路径是否存在该文件夹
BOOL isDirectory ;
//此路径是否存在
BOOL isexist=[[NSFileManager defaultManager]fileExistsAtPath:dirPath isDirectory:&isDirectory];
if (isDirectory) {
NSLog(@"YES");
}else{
NSLog(@"NO");
}
if (isexist==NO) {
NSError *error;
[[NSFileManager defaultManager]createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
if (error==nil) {
NSLog(@"成功");
}
}
三:创建一个文件
NSString *filePath=[dirPath stringByAppendingPathComponent:@"JoSone.avi"];
BOOL isCreated=[[NSFileManager defaultManager]createFileAtPath:filePath contents:nil attributes:nil];
if (isCreated) {
NSLog(@"File创建成功");
}else{
NSLog(@"File创建失败");
}
四:复制文件
NSString*toPath=[dirPath stringByAppendingPathComponent:@"JoSone(副本).avi"];
NSError *error;
BOOL isCopy=[[NSFileManager defaultManager]copyItemAtPath:filePath toPath:toPath error:&error];
if (isCopy==NO ) {
NSLog(@"error is %@",error.localizedDescription);
}
五:删除文件
BOOL isDeleted = [[NSFileManager defaultManager]removeItemAtPath:toPath error:nil];
if (isDeleted) {
NSLog(@"删除成功");
}
六:本地存储(iOS 四种持久化操作之一)
//本地存储
-(void)SaveDiction
{
//获取原始路径
NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dirPath = arr[0];
//创建文件
NSString *filePath = [dirPath stringByAppendingPathComponent:@"test.plist"];
BOOL isCreated= [[NSFileManager defaultManager]createFileAtPath:filePath contents:nil attributes:nil];
if (isCreated) {
NSLog(@"文件创建成功");
// 写入文件
NSDictionary *dict = @{@"name":@"JoSone"};
//字典写入到文件中
//atomically - YES 先放入缓冲区
[dict writeToFile:filePath atomically:YES];
}else{
NSLog(@"文件创建失败");
}
}
另外三种持久化操作为:NSUserDefaults、归档与解档、数据库。