5

I have implemented awakeFromInsert to set some default values and relationships in my core data objects. However, the method is being called twice, meaning that the to-many values I am adding are being added multiple times.

I am using parent and child managed object contexts.

What gives?

jrturton
  • 118,105
  • 32
  • 252
  • 268

2 Answers2

13

awakeFromInsert will be called when you insert the object into its initial context. When this context is saved and the changes are pushed up to the parent context, it will be called again.

You can query the self.managedObjectContext property to determine which case the method is being called for. Depending on your particular use case, you may want to check for the presence or absence of a parentContext and act accordingly.

jrturton
  • 118,105
  • 32
  • 252
  • 268
  • 4
    Am I the only one that thinks that this is a bug? Not sure if it's on your or Apples side, but the [documentation of `awakeFromInsert`](https://developer.apple.com/library/mac/documentation/cocoa/reference/CoreDataFramework/Classes/NSManagedObject_Class/Reference/NSManagedObject.html#//apple_ref/occ/instm/NSManagedObject/awakeFromInsert) explicitly says that this method is invoked only once in a objects lifetime. – Matthias Bauch Nov 08 '13 at 10:43
  • 3
    You're not the only one - see http://lists.apple.com/archives/cocoa-dev/2011/Nov/msg00734.html for more discussion. I put this question here for visibility, as that thread is pretty old. The documentation is "correct" in the sense that `self` is a different object in each context. – jrturton Nov 08 '13 at 12:15
0

thanks to jrturton help:

here is the simplest one: when parentContext is null, means when this context is saved you can do you custom logic, for example incrementing table number

- (void)awakeFromInsert
 {

     if (!self.managedObjectContext.parentContext) {
         //setting tableNumber

         [self willChangeValueForKey:@"number"];
         [self setPrimitiveNumber:tableNumber];
         [self didChangeValueForKey:@"number"];
    }

 }
Hashem Aboonajmi
  • 13,077
  • 8
  • 66
  • 75