2012-08-03 84 views
16

我的Mac应用程序是沙盒,我需要保存一个文件。我在哪里保存这个文件?我似乎无法在没有使用开放式面板的情况下找到允许进行此操作的具体位置。这是我如何在iOS上执行此操作:沙盒的Mac应用程序可以在哪里保存文件?

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *path = [paths objectAtIndex:0]; 

Mac上的沙盒目录的等效项是什么?

回答

19

该代码段适用于Mac无论您的应用程序是否为沙盒。

在非沙盒Mac应用程序中,path将引用您家中的Documents文件夹:例如, /Users/username/Documents

在沙盒应用程序中,它指的是应用程序沙箱中的文件夹:例如, /Users/username/Library/Containers/com.yourcompany.YourApp/Documents

有关详细信息,请参阅the docs

8

苹果的沙盒指南非常有用,找到了here

您基本上有一个专门用于您的应用程序的文件夹,如业余程序员在回答我的问题here时所述。

〜/库/集装箱/ com.yourcompany.yourappname/

这里是我到目前为止,我稍后会改善它:

//Create App directory if not exists: 
NSFileManager* fileManager = [[NSFileManager alloc] init]; 
NSString* bundleID = [[NSBundle mainBundle] bundleIdentifier]; 
NSArray* urlPaths = [fileManager URLsForDirectory:NSApplicationSupportDirectory 
             inDomains:NSUserDomainMask]; 

NSURL* appDirectory = [[urlPaths objectAtIndex:0] URLByAppendingPathComponent:bundleID isDirectory:YES]; 

//TODO: handle the error 
if (![fileManager fileExistsAtPath:[appDirectory path]]) { 
    [fileManager createDirectoryAtURL:appDirectory withIntermediateDirectories:NO attributes:nil error:nil]; 
} 
相关问题