Search code examples
iosswiftxcodecore-datansmanagedobject

Core Data prevent saving


Is there a way to prevent specific NSManagedObjectModel from being saved based on a specific condition?

I know we can use willSave to modify the object before saving, but is there a way to prevent an object from being saved?

override public func willSave() {

    if self.name != nil {

       // Save the object into context
    }
    else {
       // Don't save the object into context
    }
}

The reason for this request is that the user should be able to start a form and insert some of the values, then he can also go to other screens and do something else that can trigger context.save() and I don't want the form to be saved if it is not completed.

I need to create this object in context since the object has a relationship to another object in context and if I create the object outside the context, I will need to change the context for all relationships.

Thanks in advance.


Solution

  • I understand you mention you'd rather not use different conext, but using a different context is the best way really.

    If you create on your main context, even without saving, the data is still 'in context'. Separating out is safest. Creating a child context from your main context...

    let childContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    
    childContext.parent = YOUR_MAIN_THREAD_CONTEXT
    

    you now create your NSManagedObject using this child context and if the user leaves without completing then simply set this context to nil and it's away.

    If you want to commit it, then save the child context, which pushes it to main, then save the main context to push to persistent store

    func commitContext(childContext: NSManagedObjectContext?) {
    
        do {
            try childContext?.save()
            do {
                try MainThreadMoc.save()
            } catch {
                print("Error saving parent context")
            }
        } catch {
            print("Error saving childContext")
        }
    }