我正在尝试关注这个 tutorial 为了在我的应用程序中保存 UIWebView 的本地缓存。
我不得不将几行代码转换为 swift 2,但是当添加到 NSManagedObjectContext 中并保存 NSError 类型的参数时,我找不到解决问题的方法。
从图中你可以更好地理解我的意思。
我该如何解决这个问题? 我使用的代码是:
func saveCachedResponse () {
print("Saving cached response")
// 1
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = delegate.managedObjectContext!
// 2
let cachedResponse = NSEntityDescription.insertNewObjectForEntityForName("CachedURLResponse", inManagedObjectContext: context) as NSManagedObject
cachedResponse.setValue(self.mutableData, forKey: "data")
cachedResponse.setValue(self.request.URL!.absoluteString, forKey: "url")
cachedResponse.setValue(NSDate(), forKey: "timestamp")
cachedResponse.setValue(self.response.MIMEType, forKey: "mimeType")
cachedResponse.setValue(self.response.textEncodingName, forKey: "encoding")
// 3
var error: NSError?
let success = context.save(&error)
if !success {
print("Could not cache the response")
}
}
最佳答案
表面误差
处理 print("Could not cache the response") 未在其他答案中列出:
do {
try context.save()
} catch let error {
print("Could not cache the response \(error)")
}
避免数据库损坏,对所有 MOC 访问使用执行 block
因为我喜欢代码示例有点健壮,这里有一个更详尽的解决方案:
func saveCachedResponse (context: NSManagedObjectContext) {
context.performBlockAndWait({ () -> Void in
let cachedResponse = NSEntityDescription.insertNewObjectForEntityForName("CachedURLResponse", inManagedObjectContext: context) as NSManagedObject
cachedResponse.setValue(self.mutableData, forKey: "data")
// etc.
do {
try context.save()
} catch let error {
print("Could not cache the response \(error)")
}
})
}
关于ios - Swift 2 - CoreData - NSManagedObjectContext 无法使用类型为 'save' 的参数列表调用 '(inout NSError?)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31639436/