0
votes

I have the following code:

func saveContext () {
    var error: NSError? = nil
    let managedObjectContext = self.managedObjectContext
    if managedObjectContext != nil {
        if managedObjectContext.hasChanges && !managedObjectContext.save(){
            abort()
        }
    }
}

I got two errors: call can throw, but not marked with try and the error is not handled. The other one says cannot convert value of type () to expected argument type 'Bool'.

How can I fix this?

2
what is your deployment target? - Retterdesdialogs
Note that there are many Q&A's about [swift] call can throw, but not marked with try ... - Martin R

2 Answers

3
votes

The documentation for NSManagedObjectContext save() is misleading. It doesn't actually have a return value in Swift. Instead, it can throw an error.

Your two errors are because you are ignoring the throws and treating it like it returns a Bool.

Your code needs to be something like:

func saveContext () {
    var error: NSError? = nil
    let managedObjectContext = self.managedObjectContext
    if managedObjectContext != nil {
        if managedObjectContext.hasChanges {
            do {
                try managedObjectContext.save()
            } catch {
                print("Unable to save: \(error)")
                abort()
            }
        } else {
            abort()
        }
    }
}
0
votes
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedContext = appDelegate.persistentContainer.viewContext

    do {
        try managedContext.save()

    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }