Why is awakeFromInsert called twice?
Asked Answered
T

2

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?

Taka answered 8/11, 2013 at 9:56 Comment(2)
are you calling [super awakeFromInsert];?Dorcasdorcea
I wasn't, thanks for that, but it still calls it twice.Taka
T
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.

Taka answered 8/11, 2013 at 9:56 Comment(2)
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 explicitly says that this method is invoked only once in a objects lifetime.Dorcasdorcea
You're not the only one - see 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.Taka
F
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"];
    }

 }
Funiculate answered 9/9, 2014 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.