Monday 3 September 2012

Objective-C tutorials



What is Objec&ve-­C

Objective C is a programming language, which is sleeted by Apple for developing the application for iPhone and Mac systems. Here we are providing easy to learn Objective C tutorials. We will be explaining the programming language with easy to learn examples. You will find these Objective C tutorials very useful in gaining the core concepts easily and in very less time.

So, let's get started with Objective C.

Objective C tutorial
About the Objective C tutorial presented here. In this complete guide of Objective C you will be
learning the programming concepts by doing the coding. We follow the learn by doing concepts.
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.

                  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.

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.

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.

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 language is selected for the Cocoa framework.? It has several reasons.

  1. It is an Object oriented language and functionalities provided by Cocoa framework can only be delivered by object-oriented techniques.
  2. It is an extension of ANSI C so the existing C program can be use with the framework without loosing any work and user can take benefit of C language.
  With this language user can select both object oriented and procedural language as per need.
  3. It is simple and easy to learn because its syntax is small so it can make a proficient programmer with much less difficult.
  4. It is very dynamic as compared to other languages based on C. Compiler play a very important role to preserve dealing of information about objects to be use
  at the run time.
  5. It is a powerful language because decisions that might be made at compile time can be postponed until the program is running.

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.

Objective-C Hello World Example
In this section I will show you how to develop Objective C Hello World program.

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.
  
Objective C on MAC
In 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!


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


Message Expressions and comments
Like C and C++ objective-C provides comments. Programmer can use single or multi line comments in the code according to the need. Message expressions are enclosed in square brackets.

Message expressions are enclosed in square brackets as given below:
[receiver message]

Receiver can be a variable or expression that evaluates to an object (including the variable self)
■ A class name (indicating the class object)
■ super (indicating an alternative search for the method implementation)
The message is the name of a method plus any arguments passed to it.
Comments
Like C and C++ comments // and /*- - - - */ are allowed.
For example:
  1. // comment.
  2. /* comment.
      Comment. */
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++.

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<headerFile.h>
@interface ClassName:SuperClass {
     variable daclaration;
     variable daclaration;
   }
    method declaration;
    method declaration;
@end
#import<Foundation/NSObject.h>

@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<stdio.h>
#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<stdio.h>
#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 ;
}
  
Objective program with multiple parameter
Objective-C enables programmer to use method with multiple parameter. These parameter can be of same type or of different type.
This is a sample program that shows sum of three numbers as output.  

 MyClass.h
#import<Foundation/NSObject.h>
@interface MyClass:NSObject{
}

// declare method for more than one parameter
-(int) sum: (int) a andb: (int) b andc:(int)c;
@end

 MyClass.m
#import<stdio.h>
#import"MyClass.h"

@implementation MyClass
-(int) sum: (int) a andb: (int) b andc:(int)c;{
return a+b+c;
}
@end

 MyClass.m

#import<stdio.h>
#import"MyClass.m"
int main(){
MyClass *class = [[MyClass alloc]init];

printf("Sum is : %d",[class sum : 5 andb : 6 andc:10]);
[class release];
return ;
}

Output:

Sum is : 22
  
Objective C constuctors
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<Foundation/NSObject.h>
@interface MyClass:NSObject{
int a;
int b;
}
// declare constructor
-(MyClass*) set:(int) a andb:(int) b;
-(void) sum;
@end
MyClass.m
#import<stdio.h>
#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<stdio.h>
#import"MyClass.m"
int main(){

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


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 


Class Level Access
Objective-C provides facility of class level access. In the examples given above we have used '-' sign before method, '-' means instance level access. Now we will see how to define method that can be access on class level.

MyClass.h


#import<Foundation/NSObject.h>
@interface MyClass:NSObject {
 
}
   -(void)instanceShow;
   +(void)classShow;
@end
MyClass.m


#import<stdio.h>
#import"MyClass.h"
@implementation MyClass
    -(void)instanceShow {
    printf("This is instance 
level method.\n");
}
    +(void)classShow {
    printf("This is class
 level method.");
}
@end
MyClassMain.m


#import<stdio.h>
#import"MyClass.m"
int main(){
MyClass *instance = [
  [MyClass alloc]init];
[instance instanceShow];
[MyClass classShow];
[instance release];
return ;
}
Output:


This is instance level method.
This is class level method.

Here in this example we have created a method named 'classShow' that can be accessed on class level means no need to create object to use classShow() method. We can directly use this method through class name. +(void)init method is called when objective-C program starts and it calls for every class so it is the better place to define class level variable. 



Exception handling in Objective-C 

Objective-C provide exception handling to handle exceptional conditions so that code can be easier to write, easy to detect exceptions in the code and easier to maintain as well. To take support of exception handling make sure the -fobj-exceptions flag is turned on.

These are four compiler directives that are used for exception handling-

1. @try:
block of code that can throw an exception.

2. @catch:
define block of code to handle exception thrown by try block, this is usually an NSException object.

3. @finally:
defines a block of code that executed whether an exception is thrown or not.

4. @throw:
once your program detects an exception, it must propagate the exception to code that handles it. This code is called the exception handler. This entire
   process of propagating an exception is referred to as "throwing an exception?.






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. derived class only specifies how it is different with base class and everything else is taken to be the same. Here in the figure given below 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.

  


Example:

This is code of base class.

FirstClass.h  FirstClass.m

#import<Foundation/NSObject.h>
@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 <stdio.h>
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






 

 Dynamic Types in Objective-C
Objective-C provides many methods to work with dynamic types. With these methods programmer can check that object is of the given class or not, given method is member of the given class or not etc. Table given below describe some of these methods and their brief description.....

Method Description
-(BOOL) isKindOfClass: classObj is object a descendent or member of classObj
-(BOOL) isMemberOfClass: classObj is object a member of classObj
-(BOOL) respondsToSelector: selector does the object have a method named specifiec by the selector
+(BOOL) instancesRespondToSelector: selector does an object created by this class have the ability to respond to the specified selector
-(id) performSelector: selector invoke the specified selector on the object

Example:

FirstClass.h   FirstClass.m


#import<Foundation/NSObject.h>
@interface FirstClass:NSObject
-(void)fShow ;
+(void)classShow ;
@end
 
#import "FirstClass.h"
@implementation FirstClass
   -(void)fShow {
   printf("This is first class.");
   }
   +(void)classShow {
   }
@end

SecondClass.h      SecondClass.m

#import<Foundation/
      NSObject.h>
@interface SecondClass:
     NSObject
-(void)sShow;
@end
#import "SecondClass.h"
@implementation SecondClass
-(void)sShow {
   printf("This is first
       class.");
   }
@end
main.m

#import "FirstClass.m"
#import "SecondClass.m"
#import <stdio.h>
int main() {
    FirstClass *fClassObj = [[FirstClass alloc] init];
    SecondClass *sClassObj = [[SecondClass alloc] init];
    /* some methods to work with dynamic types */
    // -(BOOL) isKindOfClass: classObj  ----------- true
     if ( [fClassObj isKindOfClass: [FirstClass class]] == YES ) {
        printf( "fClassObj is kind of FirstClass.\n" );
    }
  
    // -(BOOL) isKindOfClass: classObj  ----------- false
    if ( [fClassObj isKindOfClass: [SecondClass class]] == YES ) {
        printf( "fClassObj is kind of SecondClass.\n" );
    }
    else
    printf( "fClassObj is not kind of SecondClass.\n" ); 
    // -(BOOL) isMemberOfClass: classObj ----------- true
     if ( [fClassObj isMemberOfClass: [FirstClass class]] == YES ) {
        printf( "fClassObj is member of FirstClass.\n" );
    }
    // -(BOOL) isMemberOfClass: classObj ----------- false
     if ( [sClassObj isMemberOfClass: [FirstClass class]] == YES ) {
        printf( "sClassObj is member of FirstClass.\n" );
    }
    else
    printf( "sClassObj is not member of FirstClass.\n" );
    // -(BOOL) respondsToSelector: selector ----- true
    if ( [fClassObj respondsToSelector: @selector(fShow)] == YES ) {
        printf( "fClassObj responds to fShow method\n" );
    }
    // -(BOOL) respondsToSelector: selector ----- false
    if ( [sClassObj respondsToSelector: @selector(fShow)] == YES ) {
        printf( "sClassObj responds to fShow method\n" );
    }
    else
       printf( "sClassObj does'nt respond to fShow method\n" );
    // release memory allocated for the objects
    [fClassObj release];
    [sClassObj release];
    return 0;
}
Output:
fClassObj is kind of FirstClass.
fClassObj is not kind of SecondClass.
fClassObj is member of FirstClass.
sClassObj is not member of FirstClass.
fClassObj responds to fShow method
sClassObj does'nt respond to fShow method



Objective-c memory management: retain and release
In this section we will see how to manage memory with language Objective-C. Programmer can allocate memory for the object and deallocate memory as well but we will learn what happened when object contains pointers to other objects?
Also we will see how does the Foundation framework deals with memory management when you create classes and objects.

Objective-C uses two methods retain and release. In Objective-C each object has an internal counter that is used to keep track of all references used by the objects or object has. [object retain] increments the counter by 1 and [object release] decrements the counter by 1. When counter reaches to zero, dealloc is then called.

This is simple code of memory deallocation.
-(void) dealloc {

    //show a message during deallocation.
    printf( "Deallocing fraction\n" );
    [super dealloc];
}
retainCount: retain count method is used to show the internal count of the given object so that programmer can easily increment and decrement the counter as per requirement.

Example:

MyClass.h    MyClass.m 

#import<Foundation/NSObject.h>
@interface MyClass:NSObject
  // This is MyClass declaration.
@end
#import "MyClass.h"
@implementation MyClass
  // This is MyClass definition.
@end
main.m
#import "MyClass.m"
#import <stdio.h>
int main() {
   
    // create two objects my MyClass.
    MyClass *myClassObj1 = [[MyClass alloc] init];
    MyClass *myClassObj2 = [[MyClass alloc] init];
    // current internal count of the objects.
    printf("myClassObj1 retain count is : %d \n ",
                       [myClassObj1 retainCount]);
    printf("myClassObj2 retain count is : %d \n\n",
                       [myClassObj2 retainCount]);
    // increment their counts
    [myClassObj1 retain]; // Now count is 2
    [myClassObj2 retain]; // Now count is 2
    [myClassObj1 retain]; // Now count is 3
    // print current counts.
    printf("myClassObj1 retain count is : %d \n ",
                       [myClassObj1 retainCount]);
    printf("myClassObj2 retain count is : %d \n\n ",
                       [myClassObj2 retainCount]);
    // Decrement their counts.
    [myClassObj1 release]; // Now count is 2
    [myClassObj2 release]; // Now count is 1
    [myClassObj1 release]; // Now count is 1
    // print current counts.
    printf("myClassObj1 retain count is : %d \n ",
                       [myClassObj1 retainCount]);
    printf("myClassObj2 retain count is : %d \n ",
                       [myClassObj2 retainCount]);
 
    // now deallocate both objects.
    [myClassObj1 release];
    [myClassObj1 release];
    return 0;
}

Output
:

myClassObj1 retain count is : 1 
myClassObj2 retain count is : 1 
myClassObj1 retain count is : 3 
myClassObj2 retain count is : 2 
myClassObj1 retain count is : 1 
myClassObj2 retain count is : 1 




Objective-c Dealloc

When an object contains another objects so before deallocation programmer needs to release all those objects. This example shows how to use method dealloc, when you want to deallocate an object that has already some other objects attached. 
In the example given below we have used a information system of a student, that manage three field for the student- first name, last name and email. To declare and store all these string values we have used super class NSString. We will create objects of this String class and use with the object. When we want to release the object, we need to deallocate these string objects first.

Example :

Student.h
#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>
@interface Student: NSObject {
    NSString *fName;
    NSString *lName;
    NSString *email;
}
-(void) set: (NSString*) f last: (NSString*)l email:(NSString*)e;
-(void) setFirst: (NSString*) f;
-(void) setLast: (NSString*) l;
-(void) setEmail: (NSString*) e;
-(NSString*) firstName;
-(NSString*) lastName;
-(NSString*) email;
-(void) print;
@end
Student.m

#import "Student.h"
#import <stdio.h>
@implementation Student
-(void) set: (NSString*) f last: (NSString*) l email: (NSString*)e{
    [self setFirst: f];
    [self setLast: l];
    [self setEmail: e];
}
-(NSString*) firstName {
    return fName;
}
-(NSString*) lastName {
    return lName;
}
-(NSString*) email {
    return email;
}
-(void) setFirst: (NSString*) f {
    [f retain];
    [fName release];
    fName = f;
}
-(void) setLast: (NSString*) l {
    [l retain];
    [lName release];
    lName = l;
}
-(void) setEmail: (NSString*) e {
    [e retain];
    [email release];
    email = e;
}
-(void) print {
    printf( "%s %s %s", [fName cString],[lName cString],
         [email cString] );
}
-(void) dealloc {
    [fName release];
    [lName release];
    [email release];
    [super dealloc];
}
@end

myMain.m

#import "Student.m"
#import <Foundation/NSString.h>
#import <stdio.h>
int main( int argc, const char *argv[] ) {
    NSString *fName =[[NSString alloc] initWithCString: "Mahendra"];
    NSString *lName = [[NSString alloc] initWithCString: "Singh"];
    NSString *email = [[NSString alloc] initWithCString: 
             "mahendra@roseindia.net"];
    Student *mahendra = [[Student alloc] init];
     [mahendra set: fName last: lName email: email];
    // first release string objects
    [fName release];
    [lName release];
    [email release];
    // show the retain count
    printf( "Retain count: %i\n", [mahendra retainCount]);
    [mahendra print];
    printf( "\n" );
    
    // free memory
    [mahendra release];
    return 0;
}

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 



 

No comments:

Post a Comment