Question

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.

  • Manually code the implementations of - (NSObject *)theObject & - (void)setTheObject:(NSObject *)object
  • Use @synthesize to automatically generate both methods, or
  • Use @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)

Was it helpful?

Solution

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.

OTHER TIPS

@dynamic tells the compiler that the accessor methods are provided at runtime.

With a little bit of investigation I found out that providing accessor methods override the @dynamic directive.

@synthesize tells the compiler to create those accessors for you (getter and setter)

@property tells the compiler that the accessors will be created, and that can be accessed with the dot notation or [object message]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top