iOS 专用目录



我想知道这段代码是否返回一个对应用程序专用并受应用程序沙箱保护的目录。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
return [paths firstObject];

为了自己测试这一点,我编写了两个应用程序。应用程序prateek.writer运行以下代码段:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationSupportDirectory = [paths firstObject];
NSLog(@"applicationSupportDirectory: '%@'", applicationSupportDirectory); // This is used by the second app.
NSString *filePath = [applicationSupportDirectory stringByAppendingPathComponent:@"myfile.txt"];
if (![[NSFileManager defaultManager] fileExistsAtPath:applicationSupportDirectory
                                              isDirectory:NULL]) {
  NSError *error = nil;
  if (![[NSFileManager defaultManager] createDirectoryAtPath:applicationSupportDirectory
                                       withIntermediateDirectories:YES
                                                        attributes:nil
                                                             error:&error]) {
            NSLog(@"error %@", error);
  }
}
[@"Hello World" writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

第二个应用程序 prateek.reader 运行以下代码段:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
// This string is copied from the logs of the writer application.
NSString *applicationSupportDirectory = @"/Users/prateek/Library/Developer/CoreSimulator/Devices/218F1365-5AF2-4003-83AF-6337E0EA8207/data/Containers/Data/Application/B8918247-5509-458D-AB9E-0F1273EAD2FE/Library/Application Support";
NSString *filePath = [applicationSupportDirectory stringByAppendingPathComponent:@"myfile.txt"];
NSString *string = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"Read file with contents: %@", string);

我的阅读器应用程序能够从编写器应用程序读取数据。我在iPhone 8 Plus和iPad Air模拟器上运行了这个,并看到了相同的结果。这可能与模拟器有关,或者这些是由同一开发人员(在本例中为我(创建/签名的应用程序。

"应用程序支持"文件夹特定于每个应用,并且位于应用的专用沙盒中。在真正的iOS设备上运行时,任何应用程序都无法访问另一个应用程序的此文件夹。

模拟器没有这样的限制。这是在真实设备和模拟器上运行之间的众多差异之一。

相关内容

  • 没有找到相关文章

最新更新