Understanding @synthesize in Objective-C
Q: What is the purpose of the @synthesize keyword in Objective C?
- Objective C
- Mid level question
Explore all the latest Objective C interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Objective C interview for FREE!
The `@synthesize` keyword is used in Objective-C to generate the getter and setter methods for a property declared in a class. When you declare a property in a class interface, you can use `@synthesize` in the implementation to automatically generate the accessor methods for that property.
Here's an example of using `@synthesize`:
@interface MyClass : NSObject @property (nonatomic, strong) NSString *myString; @end @implementation MyClass @synthesize myString = _myString; @end
In this example, we declare a property called `myString` in the interface of `MyClass`. In the implementation, we use `@synthesize` to generate the getter and setter methods for this property, and we specify that the instance variable backing the property should be called `_myString`.
If you don't use `@synthesize`, the compiler will automatically generate the accessor methods for you, using the same name as the property for the getter and `setPropertyName:` for the setter. However, using `@synthesize` allows you to specify a different name for the instance variable or to manually implement the accessor methods if you need more control over their behavior.
It's worth noting that in modern versions of Objective-C and Xcode, the `@synthesize` keyword is no longer required, as the compiler will automatically generate the accessor methods for you. However, you can still use `@synthesize` if you need to customize the behavior of the generated methods.


