UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

CoreData and Retrieving a single Object

Forums > SwiftUI

Hi !

I have 3 core data objects in which get pulled into a view to populate with data. I would like the user to edit one of the core data objects however, I cant seem to select which object it is. Do I have to run a for loop to cycle through and provide some if statements? Or should use some sort of fetch filter?

2      

Hello,

You could loop through the @FetchedResults and implement methods of editing each object of the loop individually. I think this is the easiest way. You could pass the elements of the loop to a new view, and use an @ObservedObject wrapper in the new view. On the new view in which you passed the element from the loop, you could implement changes and also mark the passed Core Data entity with a .objectWillChange.send() method:

                    observedElement.objectWillChange.send()

You would call the .objectWillChange.send() inside the function in which you change the managed object context to reflect the changes (like the button that saves the data):

The child view:

                @Environment(\.managedObjectContext) var moc
                @Environment(\.dismiss) var dismiss
                @ObservedObject var observedElement: ElementType

Note: I called it ElementType as an example, it is your Core Data element, how you chose to call it)

Then, in the body:

                Button {
                    observedElement.objectWillChange.send()
                    observedElement.anAttribute = newAttribute

                  if moc.hasChanges {
                        do {
                            try moc.save()
                        } catch {
                            print(error)
                        }
                    }
                    dismiss()

To retrieve a particular instance of a core data entity, you would either use an NSPredicate with some particular filtering, or you would have to implement an ID for each element and a function that retrieves that very element based on the specific ID.

For simple applications, I'd avoid this last method of retrieving data by ID.

Hope it helps!

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.