我在一个项目上遇到了问题,我已经接管了一个中途然后离开的老开发人员 - 问题是在将图像从 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/