Definitions
@synthesize will generate the getter and setter methods of the properties if the getter and/or setter has not already been implemented manually. This is what you currently believe @dynamic does.
@dynamic is used when you don’t want the runtime to automatically generate a getter and setter AND you haven’t implemented them manually. Basically, @dynamic is telling the compiler that the getter/setter will be provided dynamically at runtime or provided elsewhere, like a base class.
Usage
Since @dynamic means that the getter and setter methods are implemented elsewhere. One of the ways is to have runtime look for them in a Base class.
For example, say we have a Base class, and we implement the getter/setter methods like so:
1 2 3 4 5 6 7 |
@implementation Base //property (self.publicAge), hence the iVar is _publicAge @synthesize publicAge = _publicAge; //property (self.publicName) uses publicName, hence iVar would be _publicName @synthesize publicName = _publicName; |
When we use self.publicAge, we use the getter/setter properties generated by the compiler. If we want to manipulate the instance variable itself, we use _publicAge.
Same goes for publicName.
If we want to write our own customizable methods, we’d do:
1 2 3 4 5 6 7 8 9 10 |
//custom getter / setter -(int)publicAge { NSLog(@"Base.m - publicAge....called from %@", [self class]); return _publicAge; } -(void)setPublicAge:(int)newAge{ NSLog(@"Base.m - setPublicAge...called from %@", [self class]); _publicAge = newAge; } |
In which case we over-ride the get/set methods generated by the compiler with our own custom get set methods. Whether you want to use the generated or your own custom methods is both fine, depending on your needs.
Using @dynamic
Now this is where using @dynamic comes in.
Say you have a class Child1, which is derived from the Base class.
@dyanmic means the getter/setter methods are implemented by the self class, but somewhere else
like superclass (Base), or be provided at runtime.
1 2 3 4 5 6 7 8 9 |
@implementation Child1 @dynamic publicAge; @dynamic publicName; ... ... @end |
Hence when you use the properties
1 2 |
int i = [child1 publicAge]; NSString * name = [child1 publicName]; |
they will use Base’s publicAge and publicName getter/setter methods.