AwakeFromInsert called twice with nested contexts

This project uses Mogenerator and Magical Record. I found an error in that the call awakeFromInsertis called twice. Once for each of my contexts, I guess. This is a problem because I need to listen to NSNotifications in this NSManagedObject as follows:

- (void)awakeFromInsert
{
    // Listen for a return from background mode
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enteringForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}

But awakeFromInsert is called twice, which is pretty annoying. I want to call the ONCE method when NSManagedObject is first created.

After searching, this solution seems to make a lot of sense . However, I do not see how to add a category to NSManagedObject when using Mogenerator and MagicalRecord. Without some complicated redefinition.

The MagicalRecord MR_createEntitycalls

if ([self respondsToSelector:@selector(insertInManagedObjectContext:)]) 
    {
        id entity = [self performSelector:@selector(insertInManagedObjectContext:) withObject:context];
        return entity;
    }

Is there a clearer solution to this problem?

+1
3

, , , , . NSManagedObject:

+ (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc_ {

    JWBoard *newobject = [super insertInManagedObjectContext:moc_];
    [JWBoard awakeFromCreate:newobject];
    return newobject;
}

+ (void)awakeFromCreate:(JWBoard *)board
{
    // do setup stuff & add observers
}

!

+1

!

! , awakeFromInsert , , , "parentProcessSaveRequest". - awakeFromInsert, parentProcessSaveRequest.

, :

- (void) awakeFromInsert 
{
    [super awakeFromInsert];

    NSArray* stackArray = [NSThread callStackSymbols];
    for (NSString* method in stackArray)
    {
        if ([method rangeOfString:@"_parentProcessSaveRequest"].location != NSNotFound)
        {
            NSLog(@"Parent insert %@",self.objectID);
            return;
        }        
    }
    NSLog(@"First insert %@",self.objectID);
    // Initialize here

}

- :

2014-05-19 20:53:52.964 myApp[1891:a01f] First insert 0x6000000326c0 <x-coredata:///MyEntity/t496E9B17-E170-4A7C-B7D4-7D8B92433E1C2>
2014-05-19 20:53:53.531 myApp[1891:303] Parent insert 0xdca8000eb <x-coredata://7274869F-4BF3-4B8A-9270-A64E54476AAD/MyEntity/p14122>
2014-05-19 20:53:53.537 myApp[1891:303] Parent insert 0xdca8000eb <x-coredata://7274869F-4BF3-4B8A-9270-A64E54476AAD/MyEntity/p14122>

, , , , .

, , awakeFromInsert parentProcessSaveRequest. , ! .

0

the simplest here: when parentContext is null, it means that when you save this context, you can execute custom logic, for example, increasing the number of tables

- (void)awakeFromInsert
 {

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

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

 }
0
source

All Articles