在我的应用程序中,我让用户录制了一个声音片段,然后,如果用户选择,我希望他能够删除它。
这是我使用的代码:
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);
}
问题是 fileExistsAtPath
和 isDeletableFileAtPath
返回 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
播放音频文件时起作用。
我还为 fileExistsAtPath
和 isDeletableFileAtPath
将 %@
更改为 %d
,答案是0,我想这意味着 FALSE。
文件的名称存储在数据库中,并使用此方法检索文件的路径:
-(NSString *)returnFullPathToDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
得到这个值后,我在下面的代码中使用它
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
最佳答案
您对 (error != nil) 的检查不正确。您应该将 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?
关于objective-c - iPhone/Objective-C : Can't delete a file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3404689/