iosswiftswiftuicore-datansfetchrequest

How to only fetch Objects already saved to Context and ignore Temporary Objects in CoreData and Swift?


Context

I am building an app that uses CoreData. When opening a NewEntityForm, the app creates an Object of this Entity for the User to manipulate. When the User saves his changes, it gets saved to Context, otherwise it gets discarded using object.rollback().

This means that at any time there can be Uncommitted Objects in the given Context. However, I only want to present the saved ones inside the App expect from the NewEntityForm.


Code

This Code fetches all Objects, saved to context and temporary.

FetchRequest(sortDescriptors: [SortDescriptor(\.name, order: .forward)])

Question


Solution

  • How can I adjust my FetchRequest so that it only returns Objects already saved to the Context and ignores Uncommitted Objects.

    A managed object context is often described as a "scratch pad" for objects -- it's very purpose it to keep track of new objects and changes to existing ones before they're saved. Once you save the objects in a context, everything is written back to the context's parent store. Therefore, if you want to ignore unsaved changes, you should create a new managed object context with the same parent store. Or, if the parent store is another managed object context, you can just make the fetch request in that context.