Objective-C refresher in 5 minutes

Standard

Software engineers often have to juggle multiple languages in their minds.  This tutorial is a no-frill “Cliff Notes” of Objective-C language designed for help engineers to quickly get up to speed on Objective-C.

 

Include header files

#import 

Main function

int main(int argc, char **argv)
{
   ...
}

Defining a class

Class implementation is usually placed in a *.h file. Below is a simple class definition:

@interface SampleClass:NSObject
- (void)sampleMethod;
@end

Implementing a class

Class implementation is usually placed in a *.m file:

@implementation SampleClass

- (void)sampleMethod{
   NSLog(@"Hello, World! \n");
}

@end

Note the equivalent of C language printf(“Hello, World! \n”) is NSLog(@”Hello, World! \n”).

Defining a function

- (return_type) method_name:( argumentType1 )argumentName1 
joiningArgument2:( argumentType2 )argumentName2 ... 
joiningArgumentn:( argumentTypen )argumentNamen 
{
   body of the function
}

All arguments after the first have a label before the “:” mark, for instance, joiningArgument2.  These labels should be named to indicate what the argument is, providing documentation value. Below is a C equivalent max(int num1, int num2) function:

/* function returning the max between two numbers */
- (int) max:(int) num1 secondNumber:(int) num2 
{
   /* local variable declaration */
   int result;
 
   if (num1 > num2)
   {
      result = num1;
   }
   else
   {
      result = num2;
   }
 
   return result; 
}

Block

Block is Objective-C equivalent of lambda function:

returntype (^blockName)(argumentType)= ^{
   ...
};

For example:

void (^simpleBlock)(void) = ^{
    NSLog(@"This is a block");
};

Here is an example of calling a block function:

#import 

typedef void (^CompletionBlock)();
@interface SampleClass:NSObject
- (void)performActionWithCompletion:(CompletionBlock)completionBlock;
@end

@implementation SampleClass

- (void)performActionWithCompletion:(CompletionBlock)completionBlock{

    NSLog(@"Action Performed");
    completionBlock();
}

@end

int main()
{
    /* my first program in Objective-C */
    SampleClass *sampleClass = [[SampleClass alloc]init];
    [sampleClass performActionWithCompletion:^{
        NSLog(@"Completion is called to intimate action is performed.");
    }];
    
    return 0;
}

Anatomy of a Objective-C class

In the example below, between @interface and subsequent @end holds the class definition. The Box class is a subclass of NSObject in this example, and has length, breadth as height as class variables. They are all private, except height is public, because it is defined as a @property, that is nonatomic with read-write access. What is really happening with the @property token is that read and write accessor functions are generated where @synthesize height line is added.  Note @synthesize is inside the @implementation block.

#import 

@interface Box:NSObject
{
    double length;   // Length of a box
    double breadth;  // Breadth of a box
    double height;   // Height of a box
}
@property(nonatomic, readwrite) double height; // Property

-(double) volume;

@end

@implementation Box

@synthesize height; 

-(id)init
{
   self = [super init];
   length = 1.0;
   breadth = 1.0;
   return self;
}

-(double) volume
{
   return length*breadth*height;
}

@end

int main( )
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];    
   Box *box1 = [[Box alloc]init];    // Create box1 object of type Box
   Box *box2 = [[Box alloc]init];    // Create box2 object of type Box

   double volume = 0.0;     // Store the volume of a box here
 
   // box 1 specification
   box1.height = 5.0; 

   // box 2 specification
   box2.height = 10.0;
  
   // volume of box 1
   volume = [box1 volume];
   NSLog(@"Volume of Box1 : %f", volume);
   // volume of box 2
   volume = [box2 volume];
   NSLog(@"Volume of Box2 : %f", volume);
   [pool drain];
   return 0;
}
@end

Auto release pool

The peculiar line of code:

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 

initializes an auto-release memory pool needed by Cocoa library. In practice, always add this line.

Defining class methods

In the above example, init() is Box constructor, and volume() is an argument-less function that returns a double.

Calling class methods

To call a class method, do:

[box1 volume]

Leave a Reply