Swift 2 ( executeFetchRequest ) : 错误处理

Swift 2 ( executeFetchRequest ) : error handling

我遇到了一些我无法弄清楚的代码问题。在我安装 Xcode 7 beta 并将我的 swift 代码转换为 Swift 2

之后

代码:

override func viewDidAppear(animated: Bool) {

    let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let context: NSManagedObjectContext = AppDel.managedObjectContext
    let request = NSFetchRequest(entityName: "PlayerList")

    list = Context.executeFetchRequest(request)

    tableView.reloadData()
}

截图:

从 Swift 2 开始,Cocoa 个产生错误的方法被转换为 Swift 个抛出错误的函数。

而不是 Swift 中的可选 return 值和错误参数 1.x:

var error : NSError?
if let result = context.executeFetchRequest(request, error: &error) {
    // success ...
    list = result
} else {
    // failure
    println("Fetch failed: \(error!.localizedDescription)")
}

in Swift 2 该方法现在 return 是一个非可选的并抛出错误 在错误情况下,必须使用 try-catch:

处理
do {
    list = try context.executeFetchRequest(request)
    // success ...
} catch let error as NSError {
    // failure
    print("Fetch failed: \(error.localizedDescription)")
}

有关详细信息,请参阅 "Adopting Cocoa Design Patterns" 中的 "Error Handling" 在 "Using Swift with Cocoa and Objective-C" 文档中。

var results = [YourEntity]?
results = try! self.managedObjectContext!.executeFetchRequest(fetchRequest) as! [YourEntity]

您可以试试这个代码:

let  result = (try! self.manageContext.executeFetchRequest(FetchRequest)) as! [NSManageObjectClass]

试试下面的代码

 override func viewWillAppear(animated: Bool) {

        let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
        let context = appDel.managedObjectContext
        let request = NSFetchRequest(entityName:"Users")
        do {
            let results = try context.executeFetchRequest(request)

            itemList = results as! [NSManagedObject]


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


    }

Swift 3.0 在此示例中 PlayerListNSManagedObject entity/class 名称(由 Xcode 自动创建)

let request: NSFetchRequest<PlayerList> = PlayerList.fetchRequest()

var result:[PlayerList]?
do{
      //Succes 
      result = try context.fetch(request)
   }catch let error as NSError {
      //Error 
      print("Error \(error)")
  }

print("result: \(result)")