[英]The operation couldn’t be completed. Cocoa Error 4
我在一個項目上遇到了問題,我已經接手了一個上半身然后離開的前任開發人員 - 問題是在特定的調用中將圖像從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 _ {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.