Home > Back-end >  Core Data - How to create an Instance of Core Data object without adding it to the database?
Core Data - How to create an Instance of Core Data object without adding it to the database?

Time:05-28

I have created Core Data database, and it has an entity called Item.

If I want to create an instance of Item and add it to the database, I create it using Item(context: ).

How can I create an instance of Item without adding it to the Core Data database?

I tried something like this, but the app crashes, when I run this code:

extension Item {
    static var sampleItem: Item {
        let sampleItem = Item()
        sampleItem.timestamp = Date.now
        return sampleItem
    }
}

CodePudding user response:

Without a context (and by extension, without any connection to a persistent store or managed object model), core data can't figure out how your object should behave.

If you're not interested in persistence or relationships to any actual objects, then you can create an in-memory persistent store, using the same managed object model, and create objects in there. Those objects can also be used for unit tests and SwiftUI previews.

If you are interested in throwaway, but "real" objects, that would represent real things from the database and their relationships, then create a child main queue context with a parent of your main context. Real objects from your database will then be available, and you can do whatever you like with them. Unless you save the child context, the original database will be untouched.

CodePudding user response:

You can do this if you use init(entity:insertInto:) to create the instance, because the context argument is optional. This means you have to look up the entity description first.

You get the description from a managed object context, which would be something like

let itemEntity = NSEntityDescription.entity(forEntityName: "Item", 
    in: container.viewContext)!

Then you can create an instance like this:

let uninsertedItem = Item(entity: personEntity, insertInto:nil)

Then you can work with uninsertedItem. Later on if you want to save it, insert it into a context:

container.viewContext.insert(uninsertedItem)

If you don't want to save it, don't do that, just let the object get deallocated.

  • Related