Swift 2 - CoreData - NSManagedObjectContext无法调用' save'使用类型'的参数列表(inout NSError?)'

时间:2015-07-26 16:41:01

标签: ios core-data uiwebview

我正在尝试关注此 tutorial ,以便在我的应用中保存UIWebView的本地缓存。

我必须将几行转换为swift 2但是当添加到NSManagedObjectContext保存NSError类型的参数时,我找不到解决问题的方法。

从图片中你可以更好地理解我的意思。

enter image description here

我该如何解决这个问题? 我使用的代码是:

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")
    }
}

4 个答案:

答案 0 :(得分:4)

表面错误

处理print("Could not cache the response")未在其他答案中列出:

do {
    try context.save()
} catch let error {
    print("Could not cache the response \(error)")
}

避免数据库损坏,对所有MOC访问使用执行块

由于我喜欢代码示例有点健壮,这里有一个更详尽的解决方案:

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)")
        }
    })
}

答案 1 :(得分:3)

在Swift 2.0中

要保存上下文,您必须使用[[:<name>:]]do { try ...}您的错误。

catch {...}

修改

// Save the context.
    do {
        try context.save()
    } catch {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        //print("Unresolved error \(error), \(error.userInfo)")
    }

我在Xcode 7中使用了类似的东西而我没有let entity = NSEntityDescription.entityForName("CachedURLResponse", inManagedObjectContext: context) let newCacheUrl = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) newCacheUrl.setValue(NSDate(), forKey: "timeStamp")

答案 2 :(得分:2)

do {
    try managedObjectContext.save()
} catch let error as NSError
{
    NSLog("Unresolved error \(error), \(error.userInfo)")
}

答案 3 :(得分:1)

do {
    let success = try context.save()
} catch {

}

会做到这一点。该错误与Xcode 7无关。