应用沙盒
应用沙盒结构:
应用程序包:包含了所有的资源文件和可执行文件,这个压缩包的内容是不可以修改的。
Documents:保存应用程序运行时生成的需要持久化的的数据,ITunes同步设备时会备份该目录。
Library/Caches:保存应用程序运行时生成的需要持久化的数据。ITunes同步设备时不会备份该目录,通常存放文件较大的、不需要备份的非重要数据。
tmp:临时文件目录,通常用于应用运行时创建一个文件,用完后删掉的场景。这个文件夹中的文件不能永久存储,应用没有运行时,系统可能会删除该目录下的文件,ITunes同步设备时也不会备份该目录下的文件。
Library/Preference:保存应用的所有偏好设置,IOS的Setting设置应用会在该目录查找该目录的应用设置信息。ITunes同步设备时会备份该目录。
获取应用沙盒路径
NSString * rootPath = NSHomeDirectory();//获取根目录
NSString * docPath = [rootPath stringByAppendingPathComponent:@"documents"];//追加一个路径名,自动添加斜线。
NSString * filePath = [docPath stringByAppendingPathComponent:@"haha"];
NSString * filePath2 = [filePath stringByAppendingPathExtension:@"plist"];//添加文件名的后缀
NSLog(@"%@",rootPath);
NSLog(@"%@",docPath);
NSLog(@"%@",filePath);
NSLog(@"%@",filePath2);
plist文件的读取与写入
- (NSString *)filepath
{
if(_filepath==nil){
NSString * rootPath = NSHomeDirectory();//获取根目录
NSString * docPath = [rootPath stringByAppendingPathComponent:@"documents"];//追加一个路径名,自动添加斜线。
NSString * filePath = [docPath stringByAppendingPathComponent:@"data.plist"];
_filepath = filePath;
}
return _filepath;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self save];
[self read];
}
- (void)save
{
NSArray * array = @[@"asd",@233,@"hhe"];
//将数组写入文件中,atomically代表使用安全模式
[array writeToFile:self.filepath atomically:YES];
}
- (void)read
{
//读取
NSArray * array = [NSArray arrayWithContentsOfFile:self.filepath];
NSLog(@"%@",array);
}
plist方法的缺点是只能存储NSFoundation提供的数据类型,如果存储了对象,调用writeToFile方法是不能写入的。
错误的示例:
-(void)errorSave
{
LYViewController * ly = [[LYViewController alloc]init];
NSArray * array = @[@233,ly];
//array包含了对象,无法写入
[array writeToFile:self.filepath atomically:YES];
}

浙公网安备 33010602011771号