0

I would like to initialise an object and populate it but not add it to the persistent store. I would like to have a user on a form, and add data to fields of a managedobject but only save it once the user presses the save button.

I am using the AERecord coreData wrapper if it is relevant

mfaani
  • 33,269
  • 19
  • 164
  • 293
Anton Unt
  • 1,835
  • 1
  • 21
  • 47
  • 2
    Simply don't call save on your managedObjectContext when you create your object in the managedObjectContext? In your case, **don't call** AERecord.save() –  Feb 15 '17 at 14:27

2 Answers2

1

If the user cancels, just delete object from the managed object context like this:

[object deleteInContext:managedObjectContext];

Please refer link

Community
  • 1
  • 1
Sahana Kini
  • 562
  • 2
  • 8
0

Just don't tell it what context to use when you create it. For example the designated initializer is init(entity:insertInto:), but the second argument is optional. Pass nil. Later, you can add it to the managed object context by using the insert(_:) method.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
  • https://developer.apple.com/reference/coredata/nsmanagedobject/1506357-init - If context is not nil, this method invokes [context insertObject:self] (which causes awakeFromInsert() to be invoked). In other words, doing as you suggested will not invoke awakeFromInsert and the OP have to set the default values manually. Also if he has relationships, those relationships will not be established. However, avoiding to call save on the NSManagedObjectContext , will not save and push the object to the PersistentStore as he asked for, but still give him a valid object to work with without complications –  Feb 15 '17 at 16:20
  • And your approach inserts an object into the context, potentially establishing relationships, before it is known that the object is actually needed. It also requires the extra step of deleting the object if it isn't needed-- otherwise he must never save the context again to avoid saving the unwanted object. Both methods have complications. – Tom Harrington Feb 15 '17 at 16:33
  • Let's not overcomplicate things, it's a **simple deletion**, nothing more. CoreData will take care of all the relationships and everything else for you in matter of a millionth of a second. If I had to choose between avoiding to calling awakeFromInsert() and not get all the default values on the NSManagedObject and all the other establishments and even **not having it inserted into an NSManagedObjectContext yet** (which is massive steps and complications), compared to simply call a basic deleteObject when and IF cancelled, i'd pick the latter. But I guess your answer is a valid option. –  Feb 15 '17 at 16:37