Objective C Tutorial - Objective C Class






Objective-C adds object orientation features to the C programming language.

With Objective-C we can create classes.

A class contains both data and functions.

The data and methods within a class are called members of the class.

#import <Foundation/Foundation.h>

@interface Car : NSObject

@end

@implementation Car

@end


int main (int argc, const char * argv[]){
   
    Car *car = [[Car alloc] init];
    NSLog(@"car is %@", car);
  
  
  return 0;
}

The code above generates the following result.





Syntax

A class definition starts with the keyword @interface followed by the class name and the class body.

In Objective-C, all classes are derived from the base class called NSObject.

The following code defines a class called Box.

@interface Box:NSObject
{
    //Instance variables
    double length;  
}
@property(nonatomic, readwrite) double height; // Property

@end

The instance variables are private and are only accessible inside the class implementation.

Box box1 = [[Box alloc]init];     // Create box1 object of type Box
Box box2 = [[Box alloc]init];     // Create box2 object of type Box




Program Example of a Class

@interface MyClass : NSObject {

}

@end


@implementation MyClass

- (id)init {
    if ((self = [super init])) {
        // Initialization code here.
        NSLog (@"Hello, world!");
    }
    
    return self;
}

@end


#import <Foundation/Foundation.h>
 
int main ()
{
  MyClass *testObject = [[MyClass alloc] init];
  [testObject release];
 
   return 0;
}

The code above generates the following result.

Class with getter and setter

#import <Foundation/Foundation.h>

@interface Car : NSObject{
@private
    NSString *name_;
}


@end
@implementation Car

-(void)setName:(NSString *)name{
    name_ = name;
}

-(NSString *) name{
    return name_;
}

@end


int main (int argc, const char * argv[]){
    Car *car = [[Car alloc] init];
    car.name = @"Sports Car";
    NSLog(@"car.name is %@", car.name);
    
    [car setName:@"New Car Name"];
    NSLog(@"car.name is %@", [car name]);
  
  return 0;
}

The code above generates the following result.