Reputation: 5741
If I create a core data object, then decide to discard the changes instead of saving it, how should I achieve that? As far as I know, both of the following methods work:
// 1.
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let object = CoreDataObject(context: managedObjectContext)
...
managedObjectContext.reset()
// 2.
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let object = CoreDataObject(context: managedObjectContext)
...
managedObjectContext.delete(object)
Which one should I choose?
Upvotes: 2
Views: 1376
Reputation: 767
As you want to discard changes you should use reset or rollback.
If you wanted to delete from the persistent store (records that has been saved and persisted) you had to use delete.
For instance, a record is existed in core data. you fetch it and delete it.
but you have fetched some records but you want to discard this fetching you should use reset
reset: It give you a clean NSManagedObjectContext with no objects in it.
rollback: It discards unsaved changes.
from https://developer.apple.com/documentation/coredata/nsmanagedobjectcontext/1506942-rollback :
Removes everything from the undo stack, discards all insertions and deletions, and restores updated objects to their last committed values.
Upvotes: 1
Reputation: 5741
I got some information from Apple's documentation:
delete(_:)
Specifies an object that should be removed from its persistent store when changes are committed.
When changes are committed, object will be removed from the uniquing tables. If object has not yet been saved to a persistent store, it is simply removed from the receiver.
And so far using the delete
method has caused no bug, comparing to unexpected crashes of reset
.
Upvotes: 2