4

There is previous post about difference of @synthesize and @dynamic.

I wanna to know more about dynamic from the perspective of how to use @dynamic usually.

Usually we use @dynamic together with NSManagedObject

// Movie.h
@interface Movie : NSManagedObject {
}
@property (retain) NSString* title;
@end

// Movie.m
@implementation Movie
@dynamic title;
@end

Actually there are no generated getter/setter during compiler time according to understanding of @dynamic, so it is necessary to implement your own getter/setter.

My question is that in this NSManagedObject case, what is the rough implementation of getter/setter in super class NSManagedObject ?

Except above case, how many other cases to use @dynamic ?

Thanks,

Community
  • 1
  • 1
Forrest
  • 122,703
  • 20
  • 73
  • 107
  • As Justin already said, the key take-away is that `@dynamic` ***EXPLICITLY STOPS*** the compiler from making it's own accessors. If you don't have `@dynamic` (i.e., if you have nothing), "anything could happen" on the day, with different versions, etc. – Fattie Jul 04 '16 at 13:01

1 Answers1

4

@dynamic indicates to the compiler that you plan to provide your own implementation for the accessor(s), even if the compiler can't currently see them. If you omit @dynamic and don't use @synthesize, one of two things will happen:

  1. If you've only provided half an accessor (for instance, a getter without a setter on a readwrite property), or you're using GCC, the compiler will warn you.
  2. If you're using Clang to compile your code, proper accessors will be automatically generated for you. (Synthesize-by-default is not officially supported.)

@dynamic is therefore useful to prevent the compiler from doing either of the above. This might also come in handy if you implement a property in a very dynamic way, like with runtime functions, but that's rarely necessary.

Justin Spahr-Summers
  • 16,893
  • 2
  • 61
  • 79
  • 1
    Sorry, that was an experimental feature that they've since removed. Synthesized properties now need an explicit `@synthesize`. I'll update my answer. – Justin Spahr-Summers Feb 15 '12 at 17:37
  • I think you can restore you #2 point. Properties are now synthesized by default afaik (also see http://stackoverflow.com/q/11666008/6827) – Asaf R Aug 11 '15 at 08:10