2012-08-03 50 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]; 
} 
相關問題