Let’s create a simple class Car with model and year properties and getter/setter methods in Objective-C.
In Objective-C the class implementation is split into two parts, the interface definition and the implementation. The interface is defined in a .h file and the implementation in a .m file. The interface has the list of variables and method declarations.
A Car.h file with the definition for Car interface is shown below.
//Car.h
@interface Car : NSObject {
NSString* model;
int year;
}
-(int)year;
-(void) setYear:(int)input;
-(NSString*)model;
-(void) setModel:(NSString*)input;
@end
The Car interface has the model and year variables. It also has the definition of getter/setter methods. The ‘get’ prefix word is not required for the getter methods. The minus (-) sign before the method definitions indicate that they are instance methods.
The implementation class Car.m is shown below.
#import "Car.h"
@implementation Car
-(NSString*) model{
return model;
}
-(void) setModel:(NSString *)input{
model = input;
}
-(int)year{
return year;
}
-(void) setYear:(int)input{
year = input;
}
@end
Car.m implements the Car interface and provides the implementation for getter/setters of model and year.
If you want to create an object of Car class and access the methods, you can do it as shown below.
Car* car1 = [Car alloc];
[car1 setModel:@"Audi"];
[car1 setYear:2012];
NSLog(@"Model: %@, Year of make: %d",[car1 model],[car1 year]);
We have created an object of Car class ‘car1’ and assigned values to the model and year. A method is accessed using [object methodName:params] syntax in Objective-C.
Objective-C 2.0 (released long ago) provides a much easier syntax to define the accessors. We will discuss it in our next post.