Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)")
  }
 }
like image 483
Daug Avatar asked Dec 01 '16 12:12

Daug


People also ask

How to store elements of a list in an array?

Consider the following example: It is therefore recommended to create an array into which elements of List need to be stored and pass it as an argument in toArray () method to store elements if it is big enough. Otherwise a new array of the same type is allocated for this purpose.

How to convert ArrayList<Integer> to array of primitive data type in Java?

Method 4: Using streams API of collections in java 8 to convert to array of primitive int type. We can use this streams() method of list and mapToInt() to convert ArrayList<Integer> to array of primitive data type int int[] arr = list.stream().mapToInt(i -> i).toArray();

What happens when an array is passed to a list?

If the passed array doesn’t have enough space, a new array is created with same type and size of given list. If the passed array has more space, the array is first filled with list elements, then null values are filled. It throws ArrayStoreException if the runtime type of a is not a supertype of the runtime type of every element in this list.


1 Answers

Use fetch() instead of execute():

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

Or use 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)'")
           }
      }
}
like image 99
shallowThought Avatar answered Sep 20 '22 13:09

shallowThought