一、沙盒(sandbox)
出于安全的目的,应用程序只能将自己的数据和偏好设置写入到几个特定的位置上。当应用程序被安装到设备上时,系统会为其创建一个家目录,这个家目录就是应用程序的沙盒。
出于安全的目的,应用程序只能将自己的数据和偏好设置写入到几个特定的位置上。当应用程序被安装到设备上时,系统会为其创建一个家目录,这个家目录就是应用程序的沙盒。
- (void)viewDidLoad { [super viewDidLoad]; [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier]; //取得Documents中某个文件的路径 NSString *path = [[self documentFolder] stringByAppendingPathComponent:@"image.png"]; //获取tmp目录 NSString *tempPath = NSTemporaryDirectory(); //1,获取家目录路径的函数: NSString *homeDir = NSHomeDirectory(); //2,获取Documents目录路径/Caches目录路径的方法: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *docDir = [paths objectAtIndex:0]; //3,获取tmp目录路径的方法: NSString *tmpDir = NSTemporaryDirectory(); //4,获取应用程序程序包中资源文件路径的方法: //例如获取程序包中一个图片资源(apple.png)路径的方法: NSString *imagePath = [[NSBundle mainBundle]pathForResource:@"apple"ofType:@"png"]; UIImage *appleImage = [[UIImage alloc]initWithContentsOfFile:imagePath]; //代码中的mainBundle类方法用于返回一个代表应用程序包的对象。 } //取得Documents路径的方法: - (NSString *)documentFolder { return [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"]; } //补充:取得应用程序包(即bundle)的路径 - (NSString *)bundleFolder { return [[NSBundle mainBundle]bundlePath]; }
二、文件IO
1,将数据写到Documents目录:
- (BOOL)writeApplicationData:(NSData*)data toFile:(NSString*)fileName { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *docDir = [paths objectAtIndex:0]; if(!docDir) { NSLog(@"Documents directory not found!"); return NO; } NSString *filePath = [docDir stringByAppendingPathComponent:fileName]; return [data writeToFile:filePath atomically:YES]; }
2,从Documents目录读取数据:
- (NSData *)applicationDataFromFile:(NSString *)fileName { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *docDir = [paths objectAtIndex:0]; NSString *filePath = [docDir stringByAppendingPathComponent:fileName]; NSData *data = [[[NSData alloc]initWithContentsOfFile:filePath]autorelease]; return data; }