2013-05-19 235 views
0

我正在編寫需要在文件中存儲一些持久性信息的應用程序,但我在調試createFileAtPath時遇到了問題:contents:attributes:NSFileManager的函數,我已將問題簡化爲下面的一段代碼。如何在iOS應用程序的默認文檔目錄中創建文件

NSFileManager *filemgr; 
filemgr = [NSFileManager defaultManager]; 
NSString * fileName = @"newfile.txt"; 

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

NSString *filePath = [documentsDirectory stringByAppendingPathComponent: fileName]; 
NSLog(@"full path name: %@", filePath); 

// check if file exists 
if ([filemgr fileExistsAtPath: filePath] == YES){ 
    NSLog(@"File exists"); 

}else { 
    NSLog (@"File not found, file will be created"); 
    if (![filemgr createFileAtPath:filePath contents:nil attributes:nil]){ 
     NSLog(@"Create file returned NO"); 
    } 
} 

由於該函數不需要一個NSError對象,我很難找出爲什麼它返回false。

從我在這裏看到的其他例子Write a file on iOS和這裏How to programmatically create an empty .m4a file of a certain length under iOS using CoreAudio on device?應該可以將nil傳遞給內容和屬性參數。我試着指定兩個參數並收到相同的結果。

我在想這可能是一個權限問題,但我不確定下面的代碼是否是檢查目錄權限的正確方法。

if ([filemgr isWritableFileAtPath:documentsDirectory] == YES){ 
    NSLog (@"File is readable and writable"); 
} 
+0

你,或僅在一個或另一個有兩個您的測試設備,並在模擬器這個問題? –

+0

只有在此時的模擬器中,我沒有測試設備。雖然我很想知道是否有人從上面的代碼中接收到相同的輸出。 –

+1

我剛剛運行代碼,它完美地工作。第一次通過:「文件未找到,文件將被創建」,沒有錯誤。第二次:「文件存在」。 –

回答

5
// Following Code will create Directory in DocumentsDirectory 

NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 
NSString *dirName = [docDir stringByAppendingPathComponent:@"MyDir"]; 

BOOL isDir 
NSFileManager *fm = [NSFileManager defaultManager]; 
if(![fm fileExistsAtPath:dirName isDirectory:&isDir]) 
{ 
    if([fm createDirectoryAtPath:dirName withIntermediateDirectories:YES attributes:nil error:nil]) 
     NSLog(@"Directory Created"); 
    else 
     NSLog(@"Directory Creation Failed"); 
} 
else 
    NSLog(@"Directory Already Exist"); 
+0

謝謝,這是問題,我認爲由NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0]返回的路徑將存在,顯然這並非總是在模擬器中。 –

相關問題