1、沙盒
- 程序只能访问自己的沙盒
- NSHomeDirectory() 访问沙盒路径
- 沙盒下有三个目录:Documents、Library、tmp
- 图
Documents:
- 1)一般用存在程序中创建的文件
- 2)程序中浏览到的文件数据保存在该目录下
- 3)iTunes备份和恢复的时候会包括此目录
//Documents路径
NSString *address = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
Library:
- 1)存储应用的默认设置及状态信息
Library/Caches:
- 1)存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除
Library/Preferences:
- 1)目录包含应用程序的偏好设置文件。您不应该直接创建偏好设置文件,而是应该使用NSUserDefaults
//Library路径
NSString * Libraryaddress = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
//Caches路径
NSString *address = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
//
[Libraryaddress stringByAppendingFormat:@"/Caches"]
//Preferences路径
[Libraryaddress stringByAppendingFormat:@"/Preference"]
tmp:
- 1)提供一个即时创建临时文件的地方
//tmp路径
NSString *string = NSHomeDirectory();
NSString *tmp = [string stringByAppendingFormat:@"/tmp"];
//
NSString *string = NSTemporaryDirectory();
- 注意
iTunes在与iPhone同步时,备份所有的Documents和Library文件。
iPhone在重启时,会丢弃所有的tmp文件。
- 写入沙盒
NSString *string = NSTemporaryDirectory();
//NSString
NSString *stringH = @"HHHHHHHHHHHHH";
[stringH writeToFile:[string stringByAppendingString:@"HH.text"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
// NSArray/NSDictionary/NSData
NSArray *arr = [NSArray arrayWithObjects:@"1",@"2",@"3", nil];
[arr writeToFile:[string stringByAppendingString:@"arr.text"] atomically:YES];
- 删除沙盒文件
NSString *string = NSTemporaryDirectory();
NSFileManager *manager = [NSFileManager defaultManager];
[manager removeItemAtPath:[string stringByAppendingString:@"arr.text"] error:nil];
- 判断沙盒中是否有此文件
BOOL isExsit = [manager fileExistsAtPath:[string stringByAppendingString:@"HH.text"]];
NSFileManager *manager = [NSFileManager defaultManager];
NSString *imgHPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"/imgH"];
// 创建一个文件夹
if (![manager isExecutableFileAtPath:imgHPath]) {
[manager createDirectoryAtPath:imgHPath withIntermediateDirectories:YES attributes:nil error:nil];
}
//向imgH文件中添加图片
NSURL *url = [NSURL URLWithString:imgString];
NSString *pathString = [NSString stringWithFormat:@"/%@", [imgString substringFromIndex:(imgString.length - 7)]];
NSString *cachePath = [imgHPath stringByAppendingPathComponent:pathString];
NSLog(@"%@", cachePath);
// 删除imgH文件
NSString *imgHPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"/imgH"];
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager isExecutableFileAtPath:imgHPath]) {
[manager removeItemAtPath:imgHPath error:nil];
}
NSLog(@"%@", NSHomeDirectory());