Thursday, July 18, 2013

Objective C Basics For Begineers


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.

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.


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.
Objective C Introduction
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

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.
Features:
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

Objective-C’s dynamism has two major benefits:

1. It supports an open dynamic binding that creates a simple architecture to interactive user interface.

2. It enables to development of sophisticated development tools. An interface to the run time system gives a facility to access the information about application at
rum time this makes possible to monitor objective-C application.

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.
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
@interface MyClass:NSObject {
@private
int a;
int b;
}
-(void) set:(int) x andb:(int) y;
-(void) sum;
-(void)show;
@end
MyClass.m 
#import
#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
#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 



                                              
 

NSObject is the root class of most Objective-C class hierarchies. Through NSObject, objects inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.
Objective C Constructors
Objective-C enables user to define constructor with the help of self and super keywords. Like java Objective-C has parent class and programmer can access its constructor by statement [super init], this statement returns a instance of parent class which we assign to the 'self' keyword, actually 'self' plays same role as this keyword in C++ and Java. The default constructor is -(id) init statement if(self) is used to check the condition self != nil to confirm that parent class returned a new object successfully.
Example:

MyClass.h 

#import
@interface MyClass:NSObject{
int a;
int b;
}
// declare constructor
-(MyClass*) set:(int) a andb:(int) b;
-(void) sum;
@end
MyClass.m
#import
#import"MyClass.h"
@implementation MyClass
// define constructor
-(MyClass*) set:(int) x andb:(int) y {
self = [super init];
if(self) {
a=x;
b=y;
return self;
}
}
-(void) sum {
printf("Sum is : %d",a+b);
}
@end
MyClassMain.m
#import
#import"MyClass.m"
int main(){

// use constructor
MyClass *class = [[MyClass alloc] set : 10 andb : 12];
[class sum];
[class release];
return ;
}
Output:
Sum is : 22

Class and Method declaration and definitions


Because of objective-C is the extension of ANSI-C and it follows an object oriented approach so provides classes and objects. The way to declare and define classes and creation of object is little bit different from C and C++.
To declare a new class objective-C uses @interface directive.
Declaration of a simple class: MyClass.h

#import"SuperClass.h"
#import
@interface ClassName:SuperClass {
variable daclaration;
variable daclaration;
}
method declaration;
method declaration;
@end #import

@interface MyClass:NSObject{
int a;
int b;
}
-(void) setvara : (int) x;
-(void) setvarb : (int) y;
-(int) add;
@end
Definition of declared class: MyClass.m
#import
#import"MyClass.h"

@implementation MyClass
-(void) setvara :(int) x{
a=x;
}
-(void) setvarb :(int) y{
b=y;
}
-(int) add{
return a+b;
}
@end
Piecing it together
main.m
#import
#import"MyClass.m"

int main(){
MyClass *class = [[MyClass alloc]init];
[class setvara : 5];
[class setvarb : 6];
printf("Sum is : %d",[class add]);
[class release];
return ;
}

Compiling Objective C on windows
Go to the directory where hello.m example program is saved. You can use the following command.
$ cd c:/objectiveC


To compile program run the following command
$ gcc -o hello hello.m


This command will create a executable file of given name (here 'hello').
To run the program

$ ./hello

Objective C Inheritance


Objective-C enables programmer to inherit common methods and properties from other class, known as inheritance. Class from methods and properties are inherited known as Base Class and class that inherits known as Derived Class.
figure shows Vehicle is the base class and both Car and Bike are derived classes so that these classes can use methods and properties of Vehicle class.
This is code of base class.
FirstClass.h  &  FirstClass.m 

#import
@interface FirstClass:NSObject { 
}
int num1;
-(void)setNum1 :(int) x;
-(int)getNum1;
@end


#import "FirstClass.h"
@implementation FirstClass
-(void)setNum1 :(int) x {
num1 = x;
printf("num1 is : %d \n", num1);
}
-(int)getNum1 {
return num1;
}
@end
This is code of derived class.
SecondClass.h SecondClass.m 

#import "FirstClass.m"
@interface SecondClass: FirstClass {
int num2 ;
}
-(void)setNum2 :(int) y;
-(int)mul;
@end #import "SecondClass.h"
#import "FirstClass.h"
@implementation SecondClass
-(id) init {
self = [super init];
return self;
}
-(void)setNum2 :(int) y {
num2 = y ;
printf("num2 is : %d \n", num2);
}
-(int)mul {
return num2*[self getNum1];
}
@end
This is code of main class.
main.m 

#import "SecondClass.m"
#import 
int main() {
FirstClass *obj1 = [[FirstClass alloc] init];
SecondClass *obj2 = [[SecondClass alloc] init];
[obj1 setNum1 : 10 ];
[obj2 setNum2 : 15 ];
printf("Multiplication Result : %d \n",[obj2 mul]);
return 0;
}
Output:
num1 is : 10
num2 is : 15
Multiplication Result : 150

[Objective-C] Access Modifiers


 Access Modifiers
Objective-C also provides 3 access modifiers for member variables:
  • @public: no access restrictions
  • @private: accessible within the defining class
  • @protected: accessible within the defining class and by derived classes (default)
  • The default access mode is “protected
  • Access modifiers can be applied only to member variables; methods are always public.
Note that the member variables are located in the “{ }” section.
1
2
3
4
5
6
7
8
9
10
11
12
/* Product.h */
@interface Product : NSObject {
  @private
    int productId;
  @public
    NSString *productName;
    float price;
}
-(void) setProductId: (int) n;
-(int) getProductId;
@end

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* Product.m */
#import
#import "Product.h"
@implementation Product
-(void) setProductId: (int) n {
  productId = n;
}
-(void) getProductId {
  return productId;
}
@end

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* MainApp.m */
#import
#import "Product.h"
int Test() {
  Product *p = [Product new];
  [p setProductId:100];
  p->productName = @"Toy";
  p->price = 9.99;
  NSLog(@"Id: %d", [p getProductId]);
  NSLog(@"Name: %@", p->productName);
  NSLog(@"Id: %4.2f", p->price);
}
...