Objective C Basic (synthesizing properties)

The Benefit of synthesizing

Example we have class similar like this 

@interface Person : NSObject {
  int age;
  Address *address;
  NSString *name;
}

- (int)age;
- (void)setAge:(int)anAge;

- (Address *)address;
- (void)setAddress:(Address *)anAddress;

- (NSString *)name;
- (void)setName:(NSString *)aName;

// ...
@end


And by using properties, we end up with this:
@interface Person : NSObject {
  int age;
  Address *address;
  NSString *name;
}

@property int age;
@property (retain) Address *address;
@property (copy) NSString *name;

// ...
@end
*note at bold section in above code
It's not a giant difference, but it's an improvement. As well as making the code more compact.

The@implementation for the Person class looks like this:

// hand written getter and setter methods
@implementation Person

- (int)age {
  return age;
}

// assign-type setter
- (void)setAge:(int)anAge {
  age = anAge;
}

- (Address *)address {
  return address;
}

// retain-type setter
- (void)setAddress:(Address *)anAddress {
  if (address != anAddress) {
    [address release];
    address = [anAddress retain];
  }
}

- (NSString *)name {
  return name;
}

// copy-type setter
- (void)setName:(NSString *)aName {
  if (name != aName) {
    [name release];
    name = [aName copy];
  }
}

// ...

@end
That's too much unnecessary code, and memory management in the retain and copy type setters makes it more error prone than simple assign type setters.
Where @property really starts to pay off is when we combine it with @synthesize, like following code below
// synthesized getter and setter methods
@implementation Person

@synthesize age, address, name;

// ...
@end

we can define @synthesize like following code 
@implementation Person

@synthesize age;
@synthesize address, name;

// ...
@end

you can create custom setter to add some logic or validation like similar below

// synthesized getter and setter methods
// with one custom setter
@implementation Person

@synthesize age, address, name;

- (void)setAge:(int)anAge {
  age = anAge;
  if (age >= 55) {
    [[JunkMailer sharedJunkMailer] addPersonToAARPMailingList:self];
  }
}

// ...
@end


The @synthesize directive has one modifier if you would like to hide your variable name, similar like below code.
@implementation Person

@synthesize age = ageInYears, address, name;

// ...
@end


Bookmark and Share

0 comments:

Post a Comment