objective-c - 操作无法完成。 cocoa 错误 4

标签 objective-c cocoa

我在一个项目上遇到了问题,我已经接管了一个中途然后离开的老开发人员 - 问题是在将图像从 url 保存到核心数据的特定调用中它返回错误

The operation couldn't be completed. Cocoa Error 4.

据我所知,错误 4 是 NSFileNoSuchFileError - 与之关联的代码是

if (iconURL)
{
    NSURL *imageURL = [NSURL URLWithString:iconURL];
    NSData *img = [NSData dataWithContentsOfURL:imageURL];
    NSString *path = [self logoPath];
    NSLog(@" url path %@", imageURL);

NSError *error = nil;
BOOL success = [img writeToFile:path options:0 error:&error];
if (! success) {
    NSLog(@" purple monkey! %@", [error localizedDescription]);
}
}
else if ([self hasLogo])

{
    NSError *error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:[self logoPath] error:&error];
    if (error)
        NSLog(@"Error removing old logo: %@", [error localizedDescription]);
}

这是在包含世界紫猴的日志中抛出错误! - 奇怪的是它在原始项目中有效 - 我尝试了模拟器、清除模拟器、在设备上运行等的各种组合,但仍然得到相同的结果..

谢谢大家。

最佳答案

根据大众的要求,这是解决方案:

当您尝试保存文件的目录不存在时,会发生这种情况。绕过它的方法是在您保存创建尚不存在的目录时进行检查:

if (![[NSFileManager defaultManager] fileExistsAtPath:someDirPath]) {
    NSError *error = nil;
    if (![[NSFileManager defaultManager] createDirectoryAtPath:someDirPath withIntermediateDirecotries:YES attributes:nil error:&error]) {
        NSLog(@"Error: %@. %s, %i", error.localizedDescription, __PRETTY_FUNCTION__, __LINE__);
    }
}

编辑:

这是 Swift 中的等价物:

if !NSFileManager.defaultManager().fileExistsAtPath("path") {
    do {
        try NSFileManager.defaultManager().createDirectoryAtPath("path", withIntermediateDirectories: true, attributes: nil)
    } catch _ {

    }
}

关于objective-c - 操作无法完成。 cocoa 错误 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22494474/

相关文章:

Objective-C 在静态库中抛出异常。如何使用该库捕获程序中的异常?

iPhone 应用程序 : not resuming audio session in AVAudio Player

ios - 将 indexpath 标记传递给 tableview 中原型(prototype)单元格内的按钮

ios - 隐藏 iOS 标准控件的 subview 的风险

objective-c - Animate 替换 UISplitViewController 中的详细信息 View

cocoa - 以编程方式设置 NSSplitView 的一侧

objective-c - 如何更改 Objective-C/Cocoa 中状态栏项目标题的颜色?

objective-c - 以编程方式更改 NSTextView 的文本

iOS 褪色的白色背景上的强白色文本?

cocoa - 更新 NSStatusItem 的图像