2011-07-13 52 views
10

我正在構建一個在應用程序包的Documents目錄中緩存圖像的應用程序。爲了確保目錄存在,我想檢查它們是否存在,如果不存在,請在應用程序啓動時創建它們。如何在檢查目錄是否存在時避免EXC_BAD_ACCESS?

目前,我這樣做是在didFinishLaunchingWithOptions:像這樣:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 

    NSArray *directoriesToCreate = [[NSArray alloc] initWithObjects: 
            @"DirA/DirA1", 
            @"DirA/DirA2", 
            @"DirB/DirB2", 
            @"DirB/DirB2", 
            @"DirC", 
            nil]; 

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

    for (NSString *directoryToCreate in directoriesToCreate) { 

     NSString *directoryPath = [documentsPath stringByAppendingPathComponent:directoryToCreate]; 
     NSLog(directoryPath); 
     if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:YES]) { 

      NSError *directoryCreateError = nil; 
      [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath 
             withIntermediateDirectories:YES 
                 attributes:nil 
                  error:&directoryCreateError]; 


     } 

    } 

    [window addSubview:navigationController.view]; 
    [window makeKeyAndVisible]; 

    return YES; 

} 

在應用程序的第一個運行 - 當沒有目錄的存在 - 在應用程序運行,按預期的方式創建的目錄和一切運行得很好。

當應用程序終止並再次運行時,我在[NSFileManager defaultManager]fileExistsAtPath:調用上得到EXC_BAD_ACCESS信號。

我不明白的是,爲什麼當這些目錄不存在時,它運行得很好,但是當它們確實存在時它會崩潰。

任何人都可以提供任何幫助嗎?

+0

你的NSLog應該看起來像'NSLog(@「%@」,anObject);'。指定'NSLog(anObject);'在* anObject *是一個字符串時有效,因爲格式字符串應該在那個地方給出。所以,它將* anObject *作爲格式字符串。但它會崩潰它是一個其他對象,而不是一個字符串。 – EmptyStack

+0

嘗試''保留''路徑''和'文件路徑'對象並''for'循環後釋放它們。 – jamapag

回答

40

您正在以錯誤的方式使用檢查功能。第二個參數必須是一個指向一個布爾變量,它的功能後,充滿正所謂:

您正在使用的功能是這樣的:

[[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:YES]; 

但功能應該這樣使用:

BOOL isDir; 
[[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:&isDir]; 

if (isDir) { // file exists and it is directory. 
+0

這解釋了爲什麼在沒有'isDirectory'參數的情況下使用函數的原因 - 謝謝解釋原因。 – abitgone

+0

+1我真的很討厭人們不關心編譯器警告。它直接指出了這個問題。 – Eiko

+0

我關心編譯器警告 - 就是這樣,在我用iOS修補這些非常早期的階段,我並不常理解它們的含義。 – abitgone

4

isDirectory是一個(BOOL *),用於返回描述路徑是否指向目錄的布爾值。你正在傳遞一個BOOL。

如果目錄存在,它不會崩潰的原因是如果該目錄不存在,則不會設置該值。

+0

將'fileExistsAtPath:directoryPath isDirectory:YES'改爲'fileExistsAtPath:directoryPath'似乎解決了這個問題。謝謝! – abitgone

相關問題