How would one transfer an array of managed objects retrieved from Core Data using Swift/IOS via a "fetchRequest", to an array that is "identifiable"?
Example - How to make the "tasks" array "identifiable"
let fetchRequest : NSFetchRequest<Todo> = Todo.fetchRequest()
let tasks = try context?.fetch(fetchRequest)
Background:
ForEach(Data, id: \.idAttribute)The feature identified(by: .self) was replaced with the new syntax:
ForEach(filteredGrapes, id: \.id) { grape in
GrapeCell(grape: grape)
}
Using a file named ItemStore.xcdatamodeld with an entity ItemDAO defined with Generation=Class Definition enabled and having a String-attribute named title.
Note: One has to Product/Clear Build Folder and afterwards restart Xcode to make Xcode11Beta5 find the proper key path, which seems to be a bug in Xcode11Beta5.
import Foundation
import SwiftUI
import CoreData
class MyItemStore {
public static func defaultItems() -> [ItemDAO]{
let store = NSPersistentContainer(name: "ItemStore")
store.loadPersistentStores { (desc, err) in
if let err = err {
fatalError("core data error: \(err)")
}
}
let context = store.viewContext
let item = ItemDAO(context: context)
item.title = "hello you"
try! context.save()
return [
item,
item,
]
}
}
struct CoreDataView: View {
let items: [ItemDAO] = MyItemStore.defaultItems()
var body: some View {
VStack{
ForEach(items, id: \.title) { (item: ItemDAO) in
Text(item.title ?? "no title")
}
Text("hi")
}
}
}
extension Todo: Identifiable {
public var id: String {
//return self.objectID.uriRepresentation().absoluteString
return self.title!
}
}
IdentifiableThere you can add Identifiable as usual, which is not necessary though since an extension can add Identifiable too.
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