59

Objective-C has a feature called @dynamic.

Google only lists results about dynamic typing.

I rarely see this in code and I don't understand what it is used for. Can anyone explain me this? Thanks.

Fermat's Little Student
  • 5,549
  • 7
  • 49
  • 70
  • This is a duplicate of http://stackoverflow.com/questions/4524954/what-is-common-case-for-dynamic-usage/4524983#4524983 and http://stackoverflow.com/questions/1160498/synthesize-vs-dynamic-what-are-the-differences – Justin Spahr-Summers Jan 07 '11 at 02:50
  • 1
    Meaning that those two questions are also duplicates of this one and eachother, making them interchangeable. I'll accept the answer and close this. :) –  Jan 07 '11 at 03:06

1 Answers1

64

@dynamic means “my class will figure out how to respond to this at runtime.” Uses a runtime mechanism for an object to intercept messages it normally wouldn’t respond to. In the case where a Core Data db is used to store persistent data, NSManagedObject turns these into calls to -valueForKey: and -setValueForKey:.

Take a look at Lecture 12 (Fall 2010) of Stanford's iPhone development course.

Caleb
  • 124,013
  • 19
  • 183
  • 272
Penang
  • 1,305
  • 13
  • 18
  • But how can my code add properties to an object at runtime? –  Jan 07 '11 at 02:22
  • 3
    check out `` and `NSObject.h` file – xhan Jan 07 '11 at 02:31
  • 30
    @Time Machine: `@dynamic` doesn't necessarily mean the property will be added at run time, it just a way of saying to the compiler "I know I have declared the property but not implemented it in this class, but I know it will be there at run time". It could be as simple as the implementation is known to be provided by the super class. – JeremyP Jan 07 '11 at 08:49
  • @JeremyP I never said it does. I just asked how to do it. :) –  Jan 07 '11 at 17:56
  • 1
    @Time Machine: Sorry, I thought you were just asking because you couldn't see how to add properties at run time and therefore thought @dynamic is pointless. My point was that, yes there are ways to literally add properties at run time but also, it can be as simple as subclassing. – JeremyP Jan 10 '11 at 08:19
  • You can look into implementing getter and setter methods manually -(id)setPropertyName :(PropertyType)newName -(id)propertyName – henghonglee Jul 26 '13 at 17:48
  • @JeremyP I really like your explanation more than Penang's. You should post it in an answer. –  May 28 '15 at 18:12