Search code examples
swiftcore-data

Create Core Data objects without saving them - Swift


I need to create some Core Data objects outside the context, in other words, these are objects that will not need to be saved in Core Data. Based on a couple of threads I read it seems that creating the objects from inside the context without saving them is the best way to accomplish this, everything seems to be working fine but some notes from this thread got me wondering if the objects are in fact added to somewhere and need to somehow be deleted.

Mundi's Comment:

If you want to discard it, just delete the object before saving, and it will never touch the persistent store.

In the following code, I'm creating and returning a Dog object from within context by calling the unmanagedDog method, please note that objects created with this method are not saved.

Is there anything that needs to be done after creating objects this way?

Again, I'm just concerned because of @Mundi's comment, stating that the objects need to be deleted.

class DogServiceModel: ObservableObject{
    let manager: CoreDataManager

    // this creates a Dog and saves it in Core Data
    func addDog(name: String?, vaccines: Double?){
        let dog = Dog(context: manager.context)
        dog.name = name ?? ""
        dog.vaccines = vaccines ?? 0
        // some other expenses
        self.manager.save()
    }
    // this creates a dog object but does NOT save it in Core Data    
    func unmanagedDog(name: String?, vaccines: Double?)->Dog{
        let dog = Dog(context: manager.context)
        dog.name = name ?? ""
        dog.vaccines = vaccines ?? 0
        // some other expenses
        return dog
    }
}

class Calculator{
    func calculateDogPrice(dog:Dog){
        // do some calculations with the data insed the Dog object
    }
}

class OtherClass{
    let dogSM = DogServiceModel()
    let calculator = Calculator()

    func doSomethingTemporarly(){
        let unmanagedDog = dogSM.unmanagedDog(name: "Teddy", vaccines: 1500)
        
        calculator.calculateDogPrice(dog:unmanagedDog)
        // some other stuff
    }
}

Solution

  • The likely problem with that code is that unmanagedDog is inserted into the context and, although you don't save changes immediately, you're probably going to save changes at some point in the future. When you do that, unmanagedDog will be saved, because saving changes saves all changes in the context. Unless you're sure that you'll never save changes on manager.context, you need to do something if you don't want to save unmanagedDog.

    If you don't want to save it, you can do either of these:

    • Delete it before saving changes. That's fine, there's no reason not to do that if you don't want the object.
    • Create a new managed object context-- maybe a new child context of the one you're using-- and then never save changes on that context. You can still save changes on manager.context without saving objects from this new context.