If I define a property in Objective-C 2.0 as follows:
@property (readwrite, assign) NSObject *theObject;
I have to create getter & setter methods somehow. As far as I can tell, I have three options for this.
- (NSObject *)theObject
& - (void)setTheObject:(NSObject *)object
@synthesize
to automatically generate both methods, or@dynamic
to automatically generate any of the two methods that I don't choose to override.Am I understanding this correctly? Also, how does the use of different @property
arguments affect the results of @synthesize
& @dynamic
? (For example, nonatomic
& weak
)
You have misunderstood the difference between @synthesize
and @dynamic
.
@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 using some sort of runtime magic.
For example, the Objective-C Runtime Programming Guide says:
You can implement the methods `resolveInstanceMethod:` and `resolveClassMethod:`
to dynamically provide an implementation for a given selector for an instance
and class method respectively.
I suggest you read the Declared Properties section of The Objective-C Programming Language as this explains in much more detail the way @property
, @synthesize
and @dynamic
work along with all the attributes like nonatomic
and weak
.