Why is awakeFromInsert called twice?

后端 未结 2 1425
不知归路
不知归路 2021-01-13 17:31

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

相关标签:
2条回答
  • 2021-01-13 18:06

    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.

    0 讨论(0)
  • 2021-01-13 18:08

    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"];
        }
    
     }
    
    0 讨论(0)
提交回复
热议问题