iPhone/Objective C:无法删除文件

And*_*rei 9 iphone file-io file objective-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);
}
Run Code Online (Sandbox Code Playgroud)

问题是,fileExistsAtPathisDeletableFileAtPath返回null,并且removeItemAtPath不工作,并抛出这个错误,

错误:错误域= NSCocoaErrorDomain代码= 4 UserInfo = 0x391b7f0"操作无法完成.(可可错误4.)"

路径有这种形式:

/Users/andrei/Library/Application%20Support/iPhone%20Simulator/User/Applications/5472B318-FA57-4F8D-AD91-7E06E9609215/Documents/1280913694.caf
Run Code Online (Sandbox Code Playgroud)

有一个文件叫1280913694.caf,但它没有拿起它.它是否与路径的表示方式有关?

播放音频文件时路径有效AVAudioPlayer.

我也改为%@to %dfor fileExistsAtPathisDeletableFileAtPath,答案是0,我想这意味着FALSE.

文件名存储在数据库中,使用以下方法检索文件的路径:

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

获得此值后,我在以下代码中使用它

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
Run Code Online (Sandbox Code Playgroud)

Jes*_*ark 27

您的检查(错误!=无)是不正确的.您应该将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]);
    }
Run Code Online (Sandbox Code Playgroud)

相关回答: NSError:使用nil检测错误实际上是否关闭了错误报告?