1

本项目使用 Mogenerator 和 Magical Record。我已经找到了一个错误,awakeFromInsert即被调用了两次。我假设我的每个上下文都有一次。这是一个问题,因为我需要像这样在这个 NSManagedObject 上监听 NSNotifications:

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

但是 awakeFromInsert 被调用了两次,这很烦人。我想在第一次创建 NSManagedObject 时调用一次方法。

经过搜索这个解决方案似乎很有意义。但是,当使用 Mogenerator 和 MagicalRecord 时,我看不到如何将类别添加到 NSManagedObject。没有一些复杂的覆盖。

在 MagicalRecordMR_createEntity通话中

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

这个问题有更简洁的解决方案吗?

4

3 回答 3

2

好吧,这感觉很hacky,但似乎有效。我在人类可读的 NSManagedObject 类上创建了以下类方法:

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

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

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

开放更好的解决方案!

于 2013-11-10T21:20:20.423 回答
0

开放更好的解决方案!

我希望!对于苹果来说,调用 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

}

日志输出——objectId 保持不变:

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>

似乎可以保存到我拥有的任何嵌套上下文中,尽管它很丑陋。

不幸的是,我想不出任何合理的方法来确定是否在 parentProcessSaveRequest 的上下文中调用了 awakeFromInsert。加油,苹果!在这里给我们一面旗帜。

于 2014-05-20T04:33:44.723 回答
0

这是最简单的一个:当 parentContext 为 null 时,意味着保存此上下文时,您可以执行自定义逻辑,例如递增表号

- (void)awakeFromInsert
 {

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

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

 }
于 2014-09-09T19:51:17.570 回答