ios – Purpose of Synthesize

ios – Purpose of Synthesize

@synthesize in objective-c just implements property setters and getters:

- (void)setCoolWord:(NSString *)coolWord {
     _coolWord = coolWord;

- (NSString *)coolWord {
    return _coolWord;

It is true with Xcode 4 that this is implemented for you (iOS6 requires Xcode 4). Technically it implements @synthesize coolWord = _coolWord (_coolWord is the instance variable and coolWord is the property).

To access these properties use self.coolWord both for setting self.coolWord = @YEAH!; and getting NSLog(@%@, self.coolWord);

Also note, both the setter and getter can still be manually implemented. If you implement BOTH the setter and getter though you NEED to also manually include @synthesize coolWord = _coolWord; (no idea why this is).

Autosynthesis in iOS6 still requires @synthesize

  • to generate accessor methods for properties defined in a @protocol.
  • to generate a backing variable when you included your own accessors.

The second case can be verified like this:

#import <Foundation/Foundation.h>
@interface User : NSObject
@property (nonatomic, assign) NSInteger edad;
@implementation User

Type: clang -rewrite-objc main.m and check that the variable is generated. Now add accessors:

@implementation User
-(void)setEdad:(NSInteger)nuevaEdad {}
-(NSInteger)edad { return 0;}

Type: clang -rewrite-objc main.m and check that the variable is NOT generated. So in order to use the backing variable from the accessors, you need to include the @synthesize.

It may be related to this:

Clang provides support for autosynthesis of declared properties. Using
this feature, clang provides default synthesis of those properties not
declared @dynamic and not having user provided backing getter and
setter methods.

ios – Purpose of Synthesize

Im not sure how @synthesize relates to iOS6 but since Xcode 4.0, its essentially been deprecated. Basically, you dont need it! Just use the @property declaration and behind the scenes, the compiler generates it for you.

Heres an example:

@property (strong, nonatomic) NSString *name;

/*Code generated in background, doesnt actually appear in your application*/
@synthesize name = _name;

- (NSString*)name
    return _name;

- (void) setName:(NSString*)name
    _name = name;

All that code is taken care of the complier for you. So if you have an applications that have @synthesize, its time to do some cleanup.

You can view my similar question here which might help to clarify.

Leave a Reply

Your email address will not be published.