Embedding an NSPsistentStoreResult Array into an Array

Hi, I have problems with the code below. In particular, the if let statement gives Cast from NSPeristentStoreResultto an unrelated type [Item] always a warning failure. I am using Swift 3.01.

It seems that this should be easy to do. The book I am following has been written using an earlier version of Swift. Thank you for your indulgence.

func demo(){

let request = NSFetchRequest<Item>(entityName: "Item")

  do {
     if let items = try CDHelper.shared.context.execute(request) as? [Item] {
        for item in items {
           if let name = item.name {
              print("Fetched Managed Object = '\(name)'")
           }
        }
     }
  } catch {
     print("Error executing a fetch request: \(error)")
  }
 }
+4
source share
1 answer

Use fetch()instead execute():

if let items = try CDHelper.shared.context.fetch(request)
...

Or use performin your context:

 CDHelper.shared.context.perform {
      let fetchRequest: NSFetchRequest<Item> = Item.fetchRequest()            
      let items = try! fetchRequest.execute() 
      for item in items {
           if let name = item.name {
                print("Fetched Managed Object = '\(name)'")
           }
      }
}
+8
source

Source: https://habr.com/ru/post/1662529/


All Articles