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
}
}