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)")
}
}
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.
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();
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.
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)'")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With