Objective C Classes by Example
Classes are template for creating objects that combines data and behaviour. For example, let consider a real world object car. A car has properties like color, model, make and so on. Similarly, it can have behaviours like accelerate, stop and so on.
In Objective C, interfaces and implementation are used to create a class. A sample class is shown below
/* Every class interface starts with @interface keyword followed by class name. NSObject is the root class of all classes. */ @interface SampleClass:NSObject { } // Properties declaration @property(nonatomic, strong) NSString *string; // Method declaration - (void)start:(id)obj; /* Every class interface ends with @end keyword. */ @end /* Every class implementation starts with @implementation keyword followed by class name. */ @implementation SampleClass - (void)start:(id)obj{ // Method definition } /* Every class implementation ends with @end keyword. */ @end
Properties
Properties are used create setter and getter methods automatically. For example, let consider a property color declared as shown below.
@interface EezySampleClass:NSObject { NSString *_color; } @property (nonatomic, strong) NSString *color;
Here color, internally refers to an instance variable _color by default if you create classes in Mac and iOS applications. It creates getters and setters internally as shown below. You can override these methods if required. For example, if you want set color only if its a valid color. You can validate before you set.
-(NSString *)color{ return _color; } -(void)setColor:(NSString *)color{ _color = color; }
Access specifier and attributes for properties
You have various access specifiers and attributes for properties as listed below.
- readwrite and readonly - By default all properties are readwrite. You can make it readonly that denies the setter method of the property.
- atomic and nonatomic- Atomic means all-or-nothing and atomic is set by default.
- copy and assign- copy creates a copy of the set value and assign refers to the same object. By default, it is assign.
- strong and weak - memory management related where strong takes ownership and increases the retain count while weak just refer to the variable.
You know now how to create class. So in order to use these classes with properties, we need to instantiate them as objects.