为什么Core Data管理对象的+ initialize方法被调用两次? [英] Why is the +initialize method of Core Data managed objects being called twice?
问题描述
我有一个具有 + initialize
方法的托管核心数据对象。 (如果重要的话,我想使用该方法初始化一个静态变量,这是昂贵的设置)。测试初始化代码时我惊讶地发现, + initialize
方法被调用两次。
I have a managed core data object with a +initialize
method. (If it matters, I am looking to use that method to initialize a static variable that is expensive to to set up.) While testing that initialization code I was surprised to discover that the +initialize
method is getting called twice.
第一次初始化
正在调用 self
定义为(Class)MyClass
,如我所料。
The first time initialize
is being called self
is defined as (Class) MyClass
, as I would expect.
第二次初始化
正在调用 self
定义为(Class)MyClass_MyClass _
,这导致我怀疑一些不寻常的初始化为Core Data管理对象。
The second time initialize
is being called self
is defined as (Class) MyClass_MyClass_
, which leads me to suspect some sort of unusual initialization for Core Data managed objects.
虽然这不会对我造成问题(我可以测试看看静态变量是否已经被初始化,无论如何我会做,以处理ubclassing),它让我怀疑核心数据在做一些事情在对象或类生命周期,我不明白。有人可以向我解释在 MyClass_MyClass _
+ initialize
方法调用中发生了什么吗?
While this doesn't pose a problem for me (I can just test to see if the static variable has already been initialized, which I would do anyway, to handle ubclassing), it makes me suspect that Core Data is doing something in the object or class lifecycle that I don't understand. Can someone explain to me what is going on in this MyClass_MyClass_
+initialize
method invocation?
推荐答案
Core Data属性的访问器方法是在运行时动态创建的。
这通过创建子类 MyClass_MyClass _
( MyClass
)并添加
必要的方法到子类。
The accessor methods for Core Data properties are dynamically created at runtime.
This works by creating a subclass MyClass_MyClass_
(of MyClass
) and adding the
necessary methods to the subclass.
核心数据也有一些技巧隐藏事实
,你的实体的对象实际上是子类的实例:
Core Data also does some tricks to hide the fact that that the objects of your entity are actually instances of the subclass:
e = [NSEntityDescription insertNewObjectForEntityForName:@"MyClass" inManagedObjectContext:context];
NSLog(@"%@", [e class]); // --> MyClass
NSLog(@"%s", object_getClassName(e)); // --> MyClass_MyClass_
如果不为您的实体设置自定义类,也许会更加明显。
在这种情况下,输出是
Perhaps it becomes even more obvious if you don't set a custom class for your entity. In that case the output is
NSLog(@"%@", [e class]); // --> NSManagedObject
NSLog(@"%s", object_getClassName(e)); // --> NSManagedObject_MyClass_
因此 e
NSManagedObject
的实例,但实际上是动态创建的子类 NSManagedObject_< EntityName> _
的实例
。这个子类
实现所有的访问器方法(对于这个实体是唯一的)。
So e
"looks like" an instance of NSManagedObject
, but is indeed an instance
of a dynamically created subclass NSManagedObject_<EntityName>_
. This subclass
implements all the accessor methods (which are unique to this entity).
这篇关于为什么Core Data管理对象的+ initialize方法被调用两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!