0

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.

hdsenevi
  • 953
  • 2
  • 14
  • 27

1 Answers1

1

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)
}
Tom Harrington
  • 69,312
  • 10
  • 146
  • 170