Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swiftUI Core Data @FetchRequest single object

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){
                ....
            }
        }
    }
}
like image 748
georgeok Avatar asked Mar 02 '23 23:03

georgeok


2 Answers

[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

like image 158
Asperi Avatar answered Mar 04 '23 14:03

Asperi


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){
            ....
        }
    }
}
 }
like image 20
arthas Avatar answered Mar 04 '23 14:03

arthas