small medium large xlarge

Back to: All Forums  Core Data
27 Dec 2009, 01:09
Benoît Bourdon (1 post)

Hi, I’m curious and like to understand what happens behind Apple Code. I must say i’m a newbie in cocoa for mac. I have more experience in Cocoa Touch. So, if I say big mistakes, please correct me. My goal is to understand.

I post this message to understand this : “The accessors of attributes/relationships in Core Data are dynamically created at runtime.”

I understand the implication of that on the NSManagedObject implementation. All is well described in the book and in the apple doc

But I would like to understand how Apple implements the accessor at runtime. So, the mechanism used to generate the accessor at runtime. I searched on google but i found nothing and I think it’s important to understand that to understand NSManagedObject mechanisms.

This is how I see the things and please correct me if I’m wrong : By using @@dynamic, the accessor is not implemented and will be created by code at the runtime. But, what’s the code? I think Apple uses Key Value Coding for that. Say for example, we have an attribute “name” and the core data code must read the name. Core data will use [self valueForKey:@”name”]

but the accessor -(NSString*)name {…} doesn’t exist because it’s dynamically created. So, - (id)valueForUndefinedKey:(NSString *)key will be called and will manage the data flow. Am I right or not?

Also, because the name attribute is dynamically created. There is no IVAR to store the value. So I suppose core data stores all the attributes values in a dictionnary when - (void)setValue:(id)value forUndefinedKey:(NSString *)key is called. Am I right?

27 Dec 2009, 17:03
Marcus S. Zarra (284 posts)

What Apple actually does is to create a subclass of NSManagedObject for each entity you have in your model. This is done at runtime and your code does not notice it. This is one of the reasons that overriding the -init method is generally a bad idea.

In this generated subclass, Core Data implements all of the methods for your properties. However because the header is not available at compile time (because Core Data has not implemented anything yet) you get warnings. That is what the @dynamic property solves. It tells the compiler: “trust me, they will be there”.

If you create your own subclass, which is common, Core Data will still create it’s subclass but it will inject it between NSManagedObject and your subclass.

If you want to explore this a bit, put a debugger block in your NSManagedObject subclass (or any code that references an NSManagedObject) and take a look at the class name, etc.

You must be logged in to comment