2010-08-04 139 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