You are here

The @property and @synthesize directives

Let's face it, writing getters and setters is usually a useless task. In a typical Java program, you're required to do something like this:

...

private int hatSize;

public int getHatSize() {

return hatSize;

}

public void setHatSize(int hatSize) {

this.hatSize = hatSize;

}

...

That seems like a lot of unnecessary code to simply manage the hatSize property. And although we want to maintain data encapsulation, it would be great if the language could auto-generate the content for us. (And as you've guessed, Objective-C provides this capability through the @property and @synthesize directives.)

In this example, we'll replace the code for managing the property named "level" with auto-generated code.

The updated interface file:

#import <Foundation/Foundation.h>

@interface GasCan : NSObject

@property float level;

-(id) initWithSize:(int)x;

-(id) init;

-(void) pourContents;

-(int) size;

-(void)openSpout:(BOOL)x andValve:(BOOL)y;

@end

Pay attention to line 5: Instead of defining level as a standard float, we've used the @property directive.

And the updated implementation file:

#import "GasCan.h"

@implementation GasCan {

@protected

int size;

@private

BOOL spoutOpen;

BOOL valveOpen;

}

@synthesize level;

// Call the designated initializer and default the can to a size of 5

-(id) init {

return[self initWithSize:5];

}

// The designated initializer

-(id) initWithSize:(int)x {

self =[super init];

if(self){

size = x;

}

return self;

}

-(void) pourContents {

if(!spoutOpen){

NSLog(@"You can't pour the contents because the spout is not open.");

}else{

float increment =(valveOpen)?.1:.01;

while(level >0.0){

NSLog(@"Glug glug glug");

level -= increment;

}

level =0;

}

}

//-(float) level {

// return level;

//}

//-(void)setLevel: (float)l {

// level = (l > size) ? size : l;

//}

-(int) size {

return size;

}

-(void)openSpout:(BOOL)x andValve:(BOOL)y {

spoutOpen = x;

valveOpen = y;

}

@end

On line 11 of this file, I've used the @synthesize directive to automatically create a getter / setter pair. (As evidence of this, I've commented out the getter / setter code on lines 40-46)

Compiling the program and running it produces the same results. However, if you look at line 45, there's no longer a check to ensure the level increases beyond the size. In the next example, I'll combine the auto-generated getter with a custom setter.