How to use @FetchRequest
in order to retrieve a single object rather than a FetchedResults<Card>
? I only need a single object in my view. Is there an alternative way to perform a query and get a single object based on a unique attribute value, for example an ID?
struct MyCardsView: View {
@FetchRequest(entity: Card.entity(), sortDescriptors: []) var cards: FetchedResults<Card>
var body: some View {
List{
ForEach(cards){
....
}
}
}
}
[Continue my comment]... assuming we have Person
entity and somehow stored/get some id for some object, here is a demo of possible view that get that object by id and work with it
Note: NSManagedObject conforms to ObservableObject
struct DemoPersonView: View {
@ObservedObject var person: Person
init(id objectID: NSManagedObjectID, in context: NSManagedObjectContext) {
if let person = try? context.existingObject(with: objectID) as? Person {
self.person = person
} else {
// if there is no object with that id, create new one
self.person = Person(context: context)
try? context.save()
}
}
var body: some View {
VStack {
Text("User: \(person.name ?? "<Unknown>")")
// ... other possible code to manage/edit person
}
}
}
Tested with Xcode 12 / iOS 14
You can also use FetchRequest to get a single item using predicates and what's more fun is you can make them dynamic.
struct MyCardsView: View {
@FetchRequest var cards: FetchedResults<Card>
@State var name : String
init(name : String) {
_name = State(initialValue: name)
_cards = FetchRequest(sortDescriptors: [], predicate: NSPredicate(format: "cardProperty = %@", name))
}
var body: some View {
List{
ForEach(cards){
....
}
}
}
}
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