Swift 2 ( executeFetchRequest ) : error handling

前端 未结 5 1783
我寻月下人不归
我寻月下人不归 2020-11-27 07:21

I got some issue with the code that I can\'t figure out. After I installed Xcode 7 beta and convert my swift code to Swift 2

Code:

o         


        
相关标签:
5条回答
  • 2020-11-27 07:56

    As of Swift 2, Cocoa methods that produce errors are translated to Swift functions that throw an error.

    Instead of an optional return value and an error parameter as in Swift 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 the method now returns a non-optional and throws an error in the error case, which must be handled with try-catch:

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

    For more information, see "Error Handling" in "Adopting Cocoa Design Patterns" in the "Using Swift with Cocoa and Objective-C" documentation.

    0 讨论(0)
  • 2020-11-27 07:56

    Swift 3.0 In this example PlayerList is NSManagedObject entity/class name (auto created by 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)")
    
    0 讨论(0)
  • 2020-11-27 08:03

    You could try this code:

    let  result = (try! self.manageContext.executeFetchRequest(FetchRequest)) as! [NSManageObjectClass]
    
    0 讨论(0)
  • 2020-11-27 08:06

    Try the code below

     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)")
            }
    
    
        }
    
    0 讨论(0)
  • 2020-11-27 08:11
    var results = [YourEntity]?
    results = try! self.managedObjectContext!.executeFetchRequest(fetchRequest) as! [YourEntity]
    
    0 讨论(0)
提交回复
热议问题