Search code examples
ioscore-datansmanagedobjectnsmanagedobjectcontextmanagedobjectcontext

Re-inserting NSManagedObject to ManagedObjectContext


I have this instance of a NSManageObect that I create without a valid context just to use it to hold data and pass it around

convenience init() {
    let entityDescription =  NSEntityDescription.entityForName("UserEntity", inManagedObjectContext:managedContext)
    self.init(entity: entityDescription!, insertIntoManagedObjectContext: nil)
}

But sometimes it's handy for me to actually let them be tracked (saved) by Core Data as well. In those instances I do the following to add it to core data managed object context

myManagedContext.insertObject(myUserEntityObject)

This all works great.

My question is, does is actually matter whether if I re-insert the same reference to myManagedContext couple of times? Is there any down sides to this re-insertion? in my mind it shoudln't make a difference as it's inserting the same object reference.


Solution

  • It's safe as long as two conditions are true:

    1. It's the same managed object context
    2. The managed object's ID is still a temporary ID (i.e. the managed object hasn't been saved yet).

    It would be safer to make the insert call look something like

    if myUserEntityObject.objectID.isTemporaryID {
        myManagedContext.insertObject(myUserEntityObject)
    }