斯威夫特 - 额外的争论'错误'在call / nil / call中可以抛出

时间:2016-02-16 14:20:42

标签: swift core-data

我尝试使用swift核心数据。 我得到了

Nil与预期的参数类型不兼容'()'和 通话可以抛出,但没有标记为'尝试'并且没有处理错误

on" context.save(nil)"

额外的争论'错误'在电话中 on" var result:NSArray = context.executeFetchRequest(request,error:nil)"

发生了什么事?

import UIKit
import CoreData

class vcMain: UIViewController {

    @IBOutlet var txtUsername: UITextField!
    @IBOutlet var txtPassword: UITextField!

    @IBAction func btnSave(){
        var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
        var context: NSManagedObjectContext = appDel.managedObjectContext


        var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject

        newUser.setValue("Test Username", forKey: "username")
        newUser.setValue("Test Password", forKey: "password")

        print(newUser)
        print("SAVED")
        context.save(nil)

    }

    @IBAction func btnLoad(){
        var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
        var context: NSManagedObjectContext = appDel.managedObjectContext

        var request = NSFetchRequest(entityName: "Users")
        request.returnsObjectsAsFaults = false;

        var result: NSArray = context.executeFetchRequest(request, error:nil)

// - (nullable NSArray *)executeFetchRequest:(NSFetchRequest *)request error:(NSError **)error;



    }


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

1 个答案:

答案 0 :(得分:3)

NSManagedObjectContext的executeFetchRequest方法是一个抛出函数,因此您必须将它包装在do catch语句中并处理它可能抛出的任何错误。

var users: [Users]

do {
  users = try context.executeFetchRequest(request) as! [Users]
} catch {
  // handle error
}

您还可以使用试试吗?关键字,如果您以相同的方式处理所有错误:

if let users = try? context.executeFetchRequest(request) as? [Users] {

} else {
  // handle error
}

阅读:NSManagedObjectContext Class ReferenceSwift error handling