Print Shortlink

Plain Old Objective-C class – II

In the earlier post we had a simple Car class with model and year variables. The Car interface had the declarations for model and year properties and the implementation had the setter/getter methods for these.
It’s pretty frustrating to hand-toss properties all the time. You can use the @property directive to declare the properties in the interface like shown below.

@interface Car : NSObject {
    NSString* model;
    int year;
@property NSString* model;
@property int year;


In our implementation instead of defining the getter/setter for model and year you can use @synthesize directive that generates getter/setters.


#import "Car.h"
@implementation Car
  @synthesize model;
  @synthesize year;

The @synthesize directive generates a model/setModel and year/setYear methods. The ‘get’ prefix is ignored in the ‘getter’ methods generated. Also while invoking the model and year you can use the dot notation instead of using it like a method as shown below.

#import "Car.h"
int main (int argc, const char * argv[])
    Car *car1 = [Car alloc];
    car1.model = @"Cadillac";
    car1.year = 2008;
    NSLog(@"Model: %@, Year: %d",car1.model,car1.year);

Leave a Reply