Warm tip: This article is reproduced from serverfault.com, please click

Want to save Core Data but "Extensions must not contain stored properties"

发布于 2020-11-27 23:04:25

I have a Core Data class called "CloudPage", and I've added an extension for it in my code:

extension CloudPage:GalleryItem {
    // bunch of methods defined here
    func someFunc() -> Bool {
        return true
    }

It made sense to me to extend this class to have all model information reside here. I also thought it made sense for this class to know how to save an instance of itself, so I added my viewcontext to it:

extension CloudPage:GalleryItem {
    @Environment(\.managedObjectContext) private var viewContext

// ...some code...

But now swift says "Extensions must not contain stored properties". Is there a better way to do this? I would think all saving logic should reside on this model.

Questioner
Vlad the Impala
Viewed
0
Deitsch 2020-11-28 08:27:21

As the compiler already say, it is not allow to add stored properties in Extension. CloudPage is an NSManagedObject which means it is already managed by CoreData.

Anyway this is not how you work with CoreData Objects. I'll clarify some stuff

These objects are managed/loaded in a context. There are 2 types of contexts

  1. ViewContext (should be used for view purposes)
  2. BackgroundContext (should be used for loading stuff from e.g. APIs in the background)

If you update objects or add new ones, these already live in said context. To persist these objects you don't have to "push" them in there anymore like you'd do it with plain SQL (UPDATE table...). You simply have to save the context like

// context is the one you loaded the objects from and worked with
context.save()

I hope this helps, i just wanted to sum it up roughly for you to get a better understanding. Don't become desperate, CoreData has its quirks and you'll get used to it. For more details read Apples Documentation of working with Core Data.