iOS 沙盒机制的理解和使用

    xiaoxiao2023-03-24  4

    每个iOS应用都被限制在“沙盒”中,沙盒相当于一个加了仅主人可见权限的文件夹,及时在应用程序安装过程中,系统为每个单独的应用程序生成它的主目录和一些关键的子目录。苹果对沙盒有几条限制: 1. 应用程序在自己的沙盒中运作,但是不能访问任何其他应用程序的沙盒; 2. 应用之间不能共享数据,沙盒里的文件不能被复制到其他应用程序的文件夹中,也不能把其他应用文件夹复制到沙盒中; 3. 苹果禁止任何读写沙盒以外的文件,禁止应用程序将内容写到沙盒以外的文件夹中; 4. 沙盒目录里有三个文件夹: Documents——存储应用程序的数据文件,存储用户数据或其他定期备份的信息; Library下有两个文件夹,Caches存储应用程序再次启动所需的信息,Preferences包含应用程序的偏好设置文件,不可在这更改偏好设置; temp存放临时文件即应用程序再次启动不需要的文件。 沙盒的使用,包括写入沙盒, 读取沙盒, 删除沙盒 // 写入沙盒 - (void)writeReadArrPlistWithDataArr:(NSMutableArray *)dataArr { NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *docuPath = [path stringByAppendingPathComponent:bidPath]; // 获取沙盒路径 NSLog(@"docuPath: %@",docuPath); BOOL b = [dataArr writeToFile:docuPath atomically:YES]; b ? NSLog(@"写入沙盒成功") : NSLog(@"写入沙盒失败"); } // 读取沙盒文件 - (void)readReadArrPlist { NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *docuPath = [path stringByAppendingPathComponent:bidPath]; mReadArr = [NSMutableArray arrayWithContentsOfFile:docuPath]; if (!mReadArr) { mReadArr = [NSMutableArray arrayWithCapacity:0]; } } // 删除沙盒中的文件 - (void)deleteReadArrPlist { NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *docuPath = [path stringByAppendingPathComponent:bidPath]; NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager removeItemAtPath:docuPath error:nil]; }
    转载请注明原文地址: https://ju.6miu.com/read-1202266.html
    最新回复(0)