问题描述
这个项目使用Mogenerator和Magical Record。我跟踪了一个错误,事实是 awakeFromInsert
被调用两次。一次为我的每一个上下文我推定。这是一个问题,因为我需要听这NSManagedObject的NSNotifications像这样:
This project uses Mogenerator and Magical Record. I have tracked down a bug to the fact that awakeFromInsert
is getting called twice. Once for each of my contexts I presume. This is an issue because I need to listen for NSNotifications on this NSManagedObject like this:
- (void)awakeFromInsert
{
// Listen for a return from background mode
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enteringForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}
但是awakeFromInsert get被调用两次是很烦人。
But awakeFromInsert get's called twice which is rather annoying. I want to call a method ONCE when my NSManagedObject is first created.
在搜索。然而,我不能看到我可以添加一个类别到NSManagedObject当使用Mogenerator和MagicalRecord。没有一些复杂的重写。
After searching this solution seems to make a lot of sense. However I can't see how I can add a category onto NSManagedObject when using Mogenerator and MagicalRecord. Without some complex overriding.
在MagicalRecord MR_createEntity
调用
In MagicalRecord MR_createEntity
calls
if ([self respondsToSelector:@selector(insertInManagedObjectContext:)])
{
id entity = [self performSelector:@selector(insertInManagedObjectContext:) withObject:context];
return entity;
}
这个问题有没有更好的解决方案?
Is there a neater solution to this issue?
推荐答案
好吧,这感觉非常黑客,但似乎工作。我在我的人类可读的NSManagedObject类上创建了以下类方法:
Ok well this feels very hacky but appears to work. I created the following class methods on my human readable NSManagedObject class:
+ (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc_ {
JWBoard *newobject = [super insertInManagedObjectContext:moc_];
[JWBoard awakeFromCreate:newobject];
return newobject;
}
+ (void)awakeFromCreate:(JWBoard *)board
{
// do setup stuff & add observers
}
打开更好的解决方案!
这篇关于awakeFromInsert用嵌套上下文调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!