2010-08-04 97 views
9

在我的應用程序中,我讓用戶錄製聲音片段,之後如果用戶選擇,我希望他能夠刪除它。iPhone /目標C:無法刪除文件

這是我使用的代碼:

NSFileManager *fileManager = [NSFileManager defaultManager]; 
NSError *error; 
NSLog(@"File exists: %d", [fileManager fileExistsAtPath:path]); 
NSLog(@"Is deletable file at path: %d", [fileManager isDeletableFileAtPath:path]); 
[fileManager removeItemAtPath:path error:&error]; 
if (error != nil) 
{ 
    NSLog(@"Error: %@", error); 
    NSLog(@"Path to file: %@", path); 
} 

的問題是fileExistsAtPathisDeletableFileAtPath返回NULL和removeItemAtPath不工作,並拋出這個錯誤,

Error: Error Domain=NSCocoaErrorDomain Code=4 UserInfo=0x391b7f0 "Operation could not be completed. (Cocoa error 4.)"

的路徑有此表格:

/Users/andrei/Library/Application%20Support/iPhone%20Simulator/User/Applications/5472B318-FA57-4F8D-AD91-7E06E9609215/Documents/1280913694.caf 

有一個文件叫做1280913694.caf,但它沒有選擇它。它是否與路徑應該被表示的方式有關?

播放與AVAudioPlayer音頻文件時路徑工作。

我也改變了%@%dfileExistsAtPathisDeletableFileAtPath,答案是0,我想就是假。

文件的名稱被存儲在數據庫中,並以文件的路徑是用這種方法檢索:

-(NSString *)returnFullPathToDirectory 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    return documentsDirectory; 
} 

後,我得到這個值,我用它下面的代碼

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName]; 
+1

請將'-removeItemAtPath'前面的'%@'更改爲'%d'並再次運行。 – kennytm 2010-08-04 10:42:09

+0

注意file://前綴必須被移除,即轉換爲NSURL並獲得.path屬性(實際上路徑如上) – ThomasRS 2011-08-18 15:06:49

回答

26

您的檢查是不正確。您應該將BOOL設置爲方法的返回值,並使用它來處理錯誤條件,因爲方法可能成功完成,並且錯誤不會在之後爲零。所以,該文件實際上可能已被刪除,但您收到了不正確的錯誤。

如果文件不存在,您也不應嘗試刪除文件。

而且,我通常只是記錄錯誤的localizedDescription因爲這是更容易閱讀

此代碼的工作在我的項目(路徑是在別處定義):

NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    BOOL fileExists = [fileManager fileExistsAtPath:path]; 
    NSLog(@"Path to file: %@", path);   
    NSLog(@"File exists: %d", fileExists); 
    NSLog(@"Is deletable file at path: %d", [fileManager isDeletableFileAtPath:path]); 
    if (fileExists) 
    { 
     BOOL success = [fileManager removeItemAtPath:path error:&error]; 
     if (!success) NSLog(@"Error: %@", [error localizedDescription]); 
    } 

相關答案: NSError: Does using nil to detect Error actually turn off error reporting?

0

url編碼的文件路徑對我來說看起來很可疑。我在某處讀到iPhone的文件路徑應該代表URL爲URL,但我認爲空間不需要被編碼。

嘗試從您的路徑中刪除%20並再次嘗試?

+1

我讓文件路徑爲: **/Users/andrei/Library /應用程序支持/ iPhone模擬器/用戶/應用程序/ 0547AE74-AD10-4BEF-98CF-8FFF5BB2F70F/Documents/1280913694.caf ** 所以,沒有%20,現在......這很奇怪,它告訴我,文件不存在(在fileExistsAtPath處返回0),但該文件也是可刪除的(在isDeletableFileAtPath處返回1)。 錯誤仍然存​​在,並且不會刪除該文件。 – Andrei 2010-08-04 11:07:18

+0

您可以發佈您用來檢索路徑的代碼嗎? – Jasarien 2010-08-04 11:13:11

+0

作爲第二次編輯發佈在原始問題中(** edit2 **) – Andrei 2010-08-04 11:19:32

-8

試圖改變

NSFileManager *fileManager = [NSFileManager defaultManager]; 

於:(!錯誤=無)

NSFileManager *fileManager = [NSFileManager new]; 
+4

恩,沒有。他一開始就是對的。 – 2010-12-14 03:06:03

+0

這是甚至適當的目標 - C? – Jason 2013-09-11 00:32:42