Question : core data fetch request swiftui
Answered by : rohan-patel-rqz0zer3zml0
@Environment(\.managedObjectContext) var viewContext
/* This is for implmentation in swiftui
Attach this to your main app view: (yourNameApp.swift) where ContentView() is called .environment(\.managedObjectContext, persistenceController.container.viewContext)
At the head of this view also attach: var persistenceController = PersistenceController.shared
*/
@discardableResult func fetchItems() -> [Item] { var items: [Item] = [] let fetchRequest: NSFetchRequest<Item> fetchRequest = Item.fetchRequest() do { items = try self.viewContext.fetch(fetchRequest) } catch { print("Error fetching items from core data") } return items
}
Source : | Last Update : Wed, 17 Aug 22
Question : core data fetch request swiftui
Answered by : rohan-patel-rqz0zer3zml0
// For this example, the name of my Core Data Entity is 'TaskItem'
// This can be placed in any SwiftUI View Struct to declare a variable array of your core data entries that automatically refreshes on changes to the core data model
@FetchRequest( sortDescriptors: [ NSSortDescriptor(keyPath: \TaskItem.dueTime, ascending: true), NSSortDescriptor(keyPath: \TaskItem.complete, ascending: true) ], predicate: NSCompoundPredicate(andPredicateWithSubpredicates: [NSPredicate(format: "%K >= %@", #keyPath(TaskItem.dueTime), todayDateFrom! as NSDate)]), animation: .default ) var tasks: FetchedResults<TaskItem>
Source : | Last Update : Wed, 17 Aug 22