Daug Daug - 1 day ago 4
iOS Question

swift 3 cast a NSPersistentStoreResult to array

Hi I'm having trouble with the code below. Specifically the if let statement gives a Cast from

NSPeristentStoreResult
to unrelated type [Item] always fails warning. I'm using Swift 3.01.

It seems like this should be simple to do. The book I'm following was written using an earlier version of Swift. Thanks 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)")
}
}

Answer

Use fetch() instead of execute():

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

Or usee perform on 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)'")
           }
      }
}
Comments