How do I use this fetchRequest() in Swift?
You are using two different entities Countries
and Atributos
in the fetchRequest()
declaration. That indeed ambiguous. The entity must be unique.
@nonobjc public class func fetchRequest() -> NSFetchRequest<Countries> {
return NSFetchRequest<Countries>(entityName: "Countries")
}
and you have to use it
let fetchRequest : NSFetchRequest<Countries> = Countries.fetchRequest()
Note: It's highly recommended to name entities in singular form. Semantically each record represents one Country
not one Countries
. Only to-many relationships are supposed to be named in plural form.
Swift: CoreData FetchRequest within Class doesn't work
You can't use the @Environment
and @FetchRequest
outside of a View
"properly" @Environment
get initialized but usually doesn't update.
To fetch from CoreData you'll have to use the "old way". Attached you'll see the link with more information. It is old but a lot of it still applies.
let moc = …
let employeesFetch = NSFetchRequest(entityName: "Employee")
do {
let fetchedEmployees = try moc.executeFetchRequest(employeesFetch) as! [EmployeeMO]
} catch {
fatalError("Failed to fetch employees: \(error)")
}
How to use a @FetchRequest with the new searchable modifier in SwiftUI?
WWDC 2021 Bring Core Data Concurrency to Swift and SwiftUI has a great example of this right around minute 21:33
https://developer.apple.com/wwdc21/10017
struct ContentView: View {
@FetchRequest(sortDescriptors: [SortDescriptor(\Quake.time, order: .reverse)])
private var quakes: FetchedResults<Quake>
@State private var searchText = ""
var query: Binding<String> {
Binding {
searchText
} set: { newValue in
searchText = newValue
quakes.nsPredicate = newValue.isEmpty
? nil
: NSPredicate(format: "place CONTAINS %@", newValue)
}
}
var body: some View {
List(quakes) { quake in
QuakeRow(quake: quake)
}
.searchable(text: query)
}
}
How to execute Core Data NSFetchRequest in a class method?
let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
You're making a brand new managed object context here, with no backing persistent store or model. That's not the right way to do it. You need to use the same context you passed in to your SwiftUI environment object, wherever that came from.
You've said that the app delegate has an NSPersistentContainer
so I'm guessing you've used the SwiftUI / Core Data app template. In that case you need to replace the line of code above (let moc = ...
) with something like this:
let moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
If you are using the template, you can look in SceneDelegate.swift and see where the context is injected into the SwiftUI environment using similar code.
How to use @Fetchrequest outside a View
I came across the your question while trying to figure out how achieve a similar result myself. I'm guessing you may have cracked this by now, but for the benefit of those stumbling across the same question I'll have a go at answering, or at least pointing at where the answer might be be found :-)
As has been mentioned the @FetchRequest
property wrapper doesn't work outside of View components (which seems a bit of an odd functional omission)
The best alternative I've found is to implement essentially the same thing with a Combine
publisher for updates from the NSFetchedResultsController
as suggested by Apostolos in his answer here and detailed in a linked Medium post
I've put together a simple proof of concept example that tests and demonstrates the approach with iOS14 and its new life cycle management. This demo app can be found in my GitHub repo over here
Good luck.
How to use a Fetch request from xcdatamodeld?
Bharath's answer is for how to create and execute a fetch request in code. This is commonly how you'll do it. However, it's not actually the answer to your question. If you actually create a fetch request named "allCategories" in the core data model like that, this is how you use it:
let fetchRequest = self.managedObjectModel.fetchRequestTemplate(forName: "allCategories")
let fetchedObjects = self.managedObjectContext.execute(fetchRequest!)
How do I use a NSFetchRequest with an NSExpression and .dictionaryResultType as a SwiftUI @FetchRequest?
I solved this with a Singleton that gets initialized in the app root and injected into each view that needs it as a @StateObject. The Singleton gets access to the NSManagedObjectContext
via a one-time setup method. It uses the NotificationCenter
via NSManagedObjectContext.didSaveObjectsNotification
to listen to model changes and recalculate. While a Singleton isn't really popular to use in SwiftUI (often for good reason!) this one does not affect the underlying data, it just enriches and presents it.
Related Topics
Getting Reference to a Dictionary Value
Swiftui Vertically Misaligned Text
Linking Pages in Swift Playgrounds [Xcode]
Swiftui Change on Multilevel Children Published Object Change
Calling Consecutive Animations in Swift with Completion Handler
How to Delay a for Loop in Swift Without Interrupting The Main Thread
Cast While Looping Over Dictionary in Swift
Saving an Array of Nsurl to Nsuserdefaults
Realitykit - Keep Object Always in Front of Screen
Delete Tableview Cell, and Remove Data from Firebase
Problem with Frameworks in Command Line Tool
Wkwebview Calayer to Image Exports Blank Image
Load a Spritekit Scene from Another Bundle
How to Calculate The Camera Position from Vuforia Gl Matrix
How to Change The Default Skscene That Displays on Startup
Addperiodictimeobserver Is Not Called Every Millisecond
Automatically Reload Tableviewcontroller on Rewind
Swift: Check Which Value in Nsarray Is Closest to Another Given Value