(basic)Obj C Tutorial Part 1: Objective C Introduction

This section provides you the basic introduction about Objective C programming language. Objective C is very old programming language and it was designed and developed in 1980. Now Objective C has become popular once again as it is being used by Apple to developing applications for Mac system and iPhone.

Objective-C was designed by Brad Cox in his company Stepstone Corporation in early 1980’s. The Objective-C language is designed to enable a easier and powerful object-oriented programming. It works as a powerful set of extensions to the C language. Objective C takes best features from C and smalltalk. Objective C is easy to learn and has full object oriented capabilities. 

Objective C is simple and very intuitive programming language that makes the Object Oriented programming sample and sophisticated. Objective C is simple and small but it is a very powerful extension of standard ANSI C language. Objective C provides full object oriented programming capabilities just like C and all these things are done in very simple and straightforward way.

Most of the programming language provides:

  • A library of Objects
  • Necessary development tools
  • OOP’ support and related libraries
// //

Objective C provides all the above components. You can use Objective C to develop full fledge applications. Apple has selected Objective C as primary programming language for Mac machine and iPhone. So, you can use Objective C to develop applications for these devices.

Like an object oriented language Objective C revolves around objects. It has three parts:

1. inter- face
          Interface of a class is generally defined in header file suffixed .h. It is a declaration of a class.

2. implementation
         
Actual code is written in implementation of a class is generally defined in file of suffixed .m. It is a definition of a class.

3. Instantiation
        
After declaring and defining class we can be instantiated by allocating memory to the new object of the class.

In a nutshell Objective C is:

  • Extension of C programming language
  • Simple yet powerful object oriented programming language
  • Programming language adopted by Apple to develop application for Mac System and iPhone

In the next section we will learn the importance of Objective C programming language.

(basic)Obj C Tutorial Part 2: Why Objective C?


In this section we will learn about the importance of Objective C and “Why Objective C?” is used as programming language to develop applications for Mac System and iPhone.

Why we use objective c? 

It has a lot of features to make a powerful and object oriented program in a easier way. Some are listed below:

1. It is a powerful language, 
2. Easy-to-learn,
3. Object-oriented version of C, 
4. Provide dynamic binding, 
5. Run-time type identification, and persistence
6. Easy to understand code
7. Well organized language

 

(basic)Obj C Tutorial Part 3:

In this Objective C Tutorial we will provide you step-by-step information in detail. You will find this object c tutorial very useful. You can quickly learn objective c from our easy to follow tutorial. Get ready to learn Objective c in very short period of time.

Objective C>

The Objective-C programming language is the primary language selected by Apple for writing the applications for Mac, iPode and iPhone. To learn Objective-C you must have prior programming experience in C language. If you have good knowledge of C then you can learn Objective C quickly and start developing applications for iPhone and Mac operating systems. If you don’t know C, then please first spend some time to learn C programming language.

Objective C is an easy to learn language that can be mastered easily. In a few week you will find the difference and you will consider yourself as an expert  Objective C programmer. Our tutorial is well organized and supported with tested example code. You can just download and start experimenting with the code. This makes the learning process fast and easy.

About Objective-C Tutorial

This tutorial will help you learn the core concepts of objective c and then apply the same to develop applications for iPhone and Mac systems. This tutorial will help the programmers to learn the required skills to develop full-featured applications, utilizing the best features of Objective c like views and controls, menu items etc.

In this tutorial first we will create a simple objective-c program, set the environment for the code then compile and run the program. After passing through a program, will move towards learn something more about objective-c e.g. declare, define and use of the class.

// //

Following topics are covered in details in this Objective c tutorial:

  1. Objective C Fundamentals
  2. Understanding the Objective C OOPs concepts
  3. Memory management in Objective C
  4. Objective C Foundation framework
  5. Files and I/O operations
  6. Advance topics like Introspection, Categories, Forwarding, Dynamic Loading etc.

What next?

We are following the do and learn methodology. So, we will first show you how to setup your development environment and then test few programs. Once you are able to run the first program, you can go ahead and start learning and experimenting with the Objective C core concepts.

In the next few sections we will be:

  1. Setting up the development environment on Window and on Max OS Compiling and testing the application

Next section provides you an introduction to the Objective C programming Language.

In the next section we will show you how to develop the “Hello World” application in Objective C.

(Basic) Obj C Tuto Part 4 :Objective-C keywords

Here in this section we will know about the keywords used in objective-C language. Objective-C is a superset of C language, so program written in c and C++ should compile as objective-c. It provides some additional keywords, to avoid conflict with keywords in other language it uses ‘@’ at the beginning of keyword. These keyword are called Compiler Directives.

 Directives used to declare and define classes, categories and protocols:

Directive Definition
@interface used to declare of class or interface.
@implementation used to define a class or category.
@protocol used to declare a formal protocol.
@end ends the declaration, definition, category or protocol.


Directive used to specify the visibility of the instance. Default is @protected.

Directive Definition
@private Limits the scope of an instance variable to the class that declares it.
@protected Limits instance variable scope to declaring and inheriting classes.
@public Removes restrictions on the scope of instance variables.

Exception handling directives.

Directive Definition
@try Defines a block within which exceptions can be thrown.
@throw Throws an exception object.
@catch Catches an exception thrown within the preceding @try block.
@finally A block of code that is executed whether exceptions were thrown or not in a @try block.

Directive used for particular purpose.

Directive Definition
@class Declares the names of classes defined elsewhere.
@selector(method_name) It returns the compiled selector that identifies method_name.
@protocol(protocol_name) Returns the protocol_name protocol (an instance of the Protocol class). (@protocol is also valid without (protocol_name) for forward
declarations.)
@encode(type_spec) Yields a character string that encodes the type structure of type_spec.
@”string” Defines a constant NSString object in the current module and
initializes the object with the specified 7-bit ASCII-encoded string.
@”string1″ @”string2″ …
@”stringN”
Defines a constant NSString object in the currentmodule. The string
created is the result of concatenating the strings specified in the two
directives.
@synchronized() Defines a block of code that must be executed only by one thread
at a time.


Some keywords of Objective-C are not reserved outside. These are…..

in out inout bycopy
byref oneway    

Keyword for memory management in Objective-C 
These are looking as keywords but infact these are methods of root class NSObject.

alloc retain release autorelease

Some other keywords:

1.  bool is a keyword used in objective-C but its value is here YES or NO. In C and C++ it has value either TRUE or FALSE.
2. ‘super’ and ‘self’ can be treated as keywords but self is a hidden parameter to each method and super gives the instructions to the compiler that how to use self differently.

Preprocessor Directives
The preprocessor directives are special notations:

Directive Definition
// This is used to comment a single line.
#import  Like C and C++ it is used to include a file but it doesn’t include more than once.

(Basic) Obj C Tuto Part 5 :Objective C Hello World

In this section I will show you how to develop Objective C Hello World program. In the next section I will show you how to compile and execute the Objective C Hello World example on windows machine.

Create first objective-c program ‘hello.m’

This is a simple program to print Hello, World!

#include <stdio.h>
int main(void)
{
        printf("Hello, World!");
        return ;
}
// //

Save this program with .m extension here ‘hello.m’ in newly created directory c:/objectiveC.

On the unix or Mac OS x machine save the file in any of your favorite directory. In the next section we will show you how download and install GNU c compiler on your windows machine to compile the application. GNU compiler can be used to compile the Objective C programs.

(Basic) Obj C Tuto Part 6 :Access Modifiers and Garbage Collection

Previously it was a requirement to allocate and release memory manually to assist with this problem it provides a reference-counting memory management system through retain and release keywords. But it is still required to take care of memory management by the programmer.
Going one step further in version 2.0 garbage collector is implemented as a conservative collector. This enable users to use full functionality of C as well as preserves Objective-C’s ability to integrate with C++ code and libraries

Access Privileges

1. Default access in objective-C is @protected.
2. Like C++ objective-C provide public and private access modifiers as well.
3.
@protected accessifier enable access elements in the subclass.

Example:
MyClass.h

#import<Foundation/NSObject.h>
@interface MyClass:NSObject {
	@private
    int a;
    int b;
}
   -(void) set:(int) x andb:(int) y;
   -(void) sum;
   -(void)show;
@end

MyClass.m

#import<stdio.h>
#import"MyClass.h"
@implementation MyClass
  -(void) set:(int) x andb:(int) y {
    a=x;
    b=y;
}
-(void) sum {
printf("Sum is : %d \n",a+b);
}
-(void)show{
printf("value of a is : %d \n",a);
printf("value of b is : %d \n",b);
}
@end

MyClassMain.m

#import<stdio.h>
#import"MyClass.m"
int main(){
MyClass *class1 = [[MyClass alloc] init];
MyClass *class2 = [[MyClass alloc] init];
[class1 set: 10 andb :12];
[class1 show];
[class1 sum];
// This is invalid statement because variable a is private.
// class2->a = 10;
class2->b = 15;
[class2 show];
[class2 sum];
[class1 release];
[class1 release];
return ;
}

Output:

value of a is : 10 
value of b is : 12 
Sum is : 22 
value of a is : 0 
value of b is : 15 
Sum is : 15

Previously it was a requirement to allocate and release memory manually to assist with this problem it provides a reference-counting memory management system through retain and release keywords. But it is still required to take care of memory management by the programmer.
Going one step further in version 2.0 garbage collector is implemented as a conservative collector. This enable users to use full functionality of C as well as preserves Objective-C’s ability to integrate with C++ code and libraries

Access Privileges

1. Default access in objective-C is @protected.
2. Like C++ objective-C provide public and private access modifiers as well.
3.
@protected accessifier enable access elements in the subclass.

Example:
MyClass.h

#import<Foundation/NSObject.h>
@interface MyClass:NSObject {
	@private
    int a;
    int b;
}
   -(void) set:(int) x andb:(int) y;
   -(void) sum;
   -(void)show;
@end

MyClass.m

#import<stdio.h>
#import"MyClass.h"
@implementation MyClass
  -(void) set:(int) x andb:(int) y {
    a=x;
    b=y;
}
-(void) sum {
printf("Sum is : %d \n",a+b);
}
-(void)show{
printf("value of a is : %d \n",a);
printf("value of b is : %d \n",b);
}
@end

MyClassMain.m

#import<stdio.h>
#import"MyClass.m"
int main(){
MyClass *class1 = [[MyClass alloc] init];
MyClass *class2 = [[MyClass alloc] init];
[class1 set: 10 andb :12];
[class1 show];
[class1 sum];
// This is invalid statement because variable a is private.
// class2->a = 10;
class2->b = 15;
[class2 show];
[class2 sum];
[class1 release];
[class1 release];
return ;
}

Output:

value of a is : 10 
value of b is : 12 
Sum is : 22 
value of a is : 0 
value of b is : 15 
Sum is : 15

(Basic) Obj C Tuto Part 7 :Objective C on Windows


In this section you will learn how to use Objective C on Windows machine. We will download and install Objective C Windows compiler. On windows GNU C compiler can be used to compile the Objective C program.

Objective C Compiler for Windows

The GNUstep windows installer can be downloaded and installed  on the windows system to compile the Objective program. GNUset is objective c compiler for windows, that we will be using in our tutorial. The objective c compiler for windows can be downloaded from

.Follow the following steps to download and install Objective C compiler for your windows system:

 

1. Download:
Go to the site
http://www.gnustep.org/experience/Windows.html  and download the GNUsetup installer from the there. In our case the downloaded file is gnustep-system-0.19.2-setup.exe. Then double click on the downloaded file gnustep-system-0.19.2-setup.exe and install it on your system.
  

2. Set environment variable for GCC compiler (C:\GNUstep\mingw\bin\gcc.exe).
  

3.Open start -> programs -> GNUstep -> shell
 
This is like a command prompt in windows.

Congratulations! You have successfully installed the GNUsetp to compile and run Objective C program on your windows system. In the next section we will show you how to run the compile and run the Objective program on windows environment.

 

(Basic) Obj C Tuto Part 8 : Objective C on Mac

I this section we will show you how to compile and run Objective C program on Mac machine.

Compiling Objective C on Mac OS x

To Compile Objective-C Programs on Mac OS X

This is a simple process to compile and run the code. Follow the steps given below:
1. Set path to the directory where hello.m saved and compile with the following command

$ gcc -o hello hello.m \ -L /System/Library/Frameworks/Foundation.framework/Foundation

Here -L option is used to locate the library files used in the code.

2. To run the code use the command..

$ ./hello

3. Output will be…..

2008-01-26 23:10:32.983 hello[381:10b] hello world!

(Basic) Obj C Tuto Part 9 : Categories

When programmer wants to add some more functionality to the class, typically extend the class. But this is not a right way everywhere, so like ruby Objective-C also provides categories to achieve this. Categories allows programmer to add functionality to already existing classes without extending them.

In the example given below we have a class BaseClass that has some methods and the second class SubClass that is used to add a method to the BaseClass. In the main, we have created object of base class and use the method defined in the sub class.

Example:
This is code of primary class.

BaseClass.h BaseClass.m
#import<Foundation/NSObject.h>
@interface BaseClass : NSObject {
    int num1, num2;
  }
  -(void)set :(int) x and: (int) y;
  -(int)add;
  -(int)sub;
@end

 

#import”BaseClass.h”

@implementation BaseClass
    -(void)set :(int) x and: (int) y {
        num1 = x;
        num2 = y;
    }
    -(int)add {
        return num1+num2;
    }
    -(int)sub {
        if(num1>num2){
            return num1-num2;
         }
        else
            return num2-num1;
     }
@end

// //

This is code of sub class that is used to add method in the primary class.

SubClass.h SubClass.m
#import"BaseClass.h"
@interface BaseClass(Category)
  -(void)show:(int)x;
@end

 

#import"SubClass.h"
@implementation BaseClass(BaseClass)
  -(void)show:(int)x {
      printf("Result is : %d \n",x);
  }
@end

 

 

main.m

#import"BaseClass.m"
#import"SubClass.m"
#import<stdio.h>
int main(){
   BaseClass *obj = [[BaseClass alloc] init];
   [obj set:10 and:8];
   [obj show:[obj add]];
   [obj show:[obj sub]];
   [obj release];
   return 0;
}

Output:

Result is : 18 
Result is : 2 

(Basic) Obj C Tuto Part 10 : Posing

Posing is similar to category but it works a little bit different with the category. It enable programmers to pose subclass to super class globally. When subclass posed on super class method which are same in both classes are override with the subclass methods.

In the example code given below we have two classes BaseClass and SubClass. Method show() is defined in both class but with different message. Before posing when we create object of base class, show method will show the output according to the base class but after posing it will display output from show method defined in sub class.

Example:

BaseClass.h  BaseClass.m
#import<Foundation/NSObject.h>
@interface BaseClass : NSObject {
    int num1, num2;
  }
  -(void)set :(int) x and: (int) y;
  -(int)add;
  -(int)sub;
  -(void)show:(int)x;
@end

 

#import"BaseClass.h"
@implementation BaseClass
  -(void)set :(int) x and: (int) y {
       num1 = x;
       num2 = y;
  }
  -(int)add {
       return num1+num2;
  }
  -(int)sub {
       if(num1>num2){
          return num1-num2;
       }
       else
          return num2-num1;
       }
  -(void)show:(int)x {
      printf("Base class result : %d \n",x);
  }
@end

 



 

SubClass.h  SubClass.m
#import"BaseClass.h"
@interface SubClass : BaseClass
-(void)show:(int)x;
@end

 

#import"SubClass.h"
@implementation SubClass
-(void)show:(int)x {
printf("Sub class result : %d \n",x);
}
@end

 

main.m

#import"BaseClass.m"
#import"SubClass.m"
#import<stdio.h>
int main(){
   // create base class object.
   BaseClass *obj1 = [[BaseClass alloc] init];
   [obj1 set:10 and:8];
   [obj1 show:[obj1 add]];
   [obj1 show:[obj1 sub]];
   // pose subclass to baseclass.
   [SubClass poseAsClass: [BaseClass class]];
   // create base class object after posing.
   BaseClass *obj2 = [[BaseClass alloc] init];
   [obj2 set:11 and:6];
   [obj2 show:[obj2 add]];
   [obj2 show:[obj2 sub]];
   // free memory
   [obj1 release];
   [obj2 release];
   return 0;
}

Output:

Base class result : 18 
Base class result : 2 
Sub class result : 17 
Sub class result : 5