Kelvin Lau Kelvin Lau - 10 months ago 67
Objective-C Question

What does @NSManaged do?

I have encountered this keyword in various occasions. I kind of know what it's suppose to do. But I really want a better understanding of it.

What I noticed about

- based not on documentation, but through repeated use:

  1. It magically replaces key value coding.

  2. It is roughly equivalent to
    in Objective-C (which I don't know much about)

  3. I need it to subclass
    from the
    Parse SDK
    . It normally uses KVC to read/write values from/to the backend.

  4. Prefixing any variable with
    will shut the compiler up when I don't initialize within the initializer.

The formal definition (in the Core Data Apple Docs):

Core Data provides the underlying storage and implementation of properties in subclasses of the NSManagedObject class. Add the @NSManaged attribute before each property definition in your managed object subclass that corresponds to an attribute or relationship in your Core Data model. Like the @dynamic attribute in Objective-C, the @NSManaged attribute informs the Swift compiler that the storage and implementation of a property will be provided at runtime. However, unlike @dynamic, the @NSManaged attribute is available only for Core Data support.

What I got from that:

Variables with
shall be exempt from compile time checks for something.

I've read the formal documentation and various other SO questions regarding this matter:

@synthesize vs @dynamic, what are the differences?

What is common case for @dynamic usage?

I instinctively recognize some scenarios where I should use it. I partially know what it does. But what I seek is purer understanding of what it does.

Further Observations:

in the
Parse SDK
relies on
Key Value Coding
to access its values. The
provides the following accessors:


let score = results.objectForKey("descriptionOfResult")
//returns the descriptionOfResult value from the results object


results.setObject("The results for a physics exam", forKey: "descriptionOfResult")
//sets the value of descriptionOfResult

To my understanding,
magically understands that the variable I've declared automatically uses the above accessors to
. I'd like to know how it does that (if what I understand is true), and whatever else it does.

Answer Source

Yes, it kinda really acts like @dynamic -- technically it might be identical even. Semantically there is a slight difference:

@dynamic says 'compiler, don't check if my properties are also implemented. There might be no code you can see but I guarantee it will work at runtime'

@NSManaged now says 'compiler, don't check those properties as I have Core Data to take care of the implementation - it will be there at runtime'

so you could even say: @NSManaged is syntactic sugar that is a more narrow version of dynamic :)
here someone even used @NSManaged without CD because he wanted the @dynamic behaviour