沙盒机制
1.每一个APP安装到手机上(或者模拟器上)都会自动生成3个文件夹
这三个文件夹
(
Documents ,Library(Caches ,Preferences), tmp
)
可以理解为这个
App
的沙盒
2.
并且
每个
APP
的文件夹
都是相对独立的
只能自己的应用去访问
不可以互相访问
3.
文件夹中
存储的是代码以外的
所有数据
例如
(
图片素材
声音
视频
文档等
)
也就是说
咱们的持久化文件
(
缓存文件
)
可以存储到
文件夹中
-----------------------------------------------------------------------
打印沙盒的各个文件夹路径
- (void)path
{
每一次运行的时候(在重新运行模拟器中)
都是重新安装的过程
都会随机生成一个新的沙盒路径(名字是随机的)
注意:要获取的是当前的沙盒路径
注意:要获取的是当前的沙盒路径
打印沙盒主路径
NSString *appPath =NSHomeDirectory();
NSLog(@"%@",appPath);
NSLog(@"%@",appPath);
Documents 文件夹
可以被
iTunes
备份
可以保存一些用户的数据
及缓存文件等
NSDocumentDirectory要获取的文件夹路径
NSUserDomainMask搜索范围
YES是否获取全路径
NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,NO);
NSString *documentsPath = [documents lastObject];
NSLog(@"%@",documentsPath);
NSString *documentsPath = [documents lastObject];
NSLog(@"%@",documentsPath);
获取Library文件夹路径
Library
可以被
iTunes
备份
Caches
主要存储系统缓存文件
Preferences
系统配置文件
NSArray *library =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
NSString *libraryPath = [library firstObject];
NSLog(@"%@",libraryPath);
NSString *libraryPath = [library firstObject];
NSLog(@"%@",libraryPath);
获取tmp文件夹
主要存储临时文件
当手机重新启动时 该文件夹的文件会被删除
(有可能不重启也会被删除)
NSString *tmp =NSTemporaryDirectory();
NSLog(@"%@",tmp);
NSLog(@"%@",tmp);
}
-----------------------------------------------------------------------
简单对象的写入
系统的类实例出来的对象叫简单对象
例如:字符串 字典 数组 二进制对象(NSData)
如果要写入一个数组或者字典等容器类对象
那么这个容器当中也要保存是
简单对象才能写入
- (void)writeFile
{
把字符串存储到沙盒当中
NSString *str =@"第一章盘古开天";
xiaoshuo.txt
拼接文件存储的路径
NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentPath = [documents firstObject];
NSString *filePath = [documentPathstringByAppendingPathComponent:@"/xiaoshuo.txt"];
NSLog(@"%@",filePath);
进行简单对象的写入
atomically保护写入作用
在写入过程中出现意外情况也可以写入成功
[strwriteToFile:filePathatomically:YESencoding:NSUTF8StringEncodingerror:nil];
写入一个数组
NSArray *array = @[@"