Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

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.

1. About 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.
 
2. 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.
 
3. 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.
 

1. Objective C Hello World Example


In this section I will show you how to develop Objective C Hello World program.
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.
 
2. Objective C on Mac
I this section we will show you how to compile and run Objective C program on Mac
machine.
 
3. Compiling Objective C
In this section we will show you how to compile Objective C program on windows and
Max OS x machine. Compiling Objective C program is necessary as it generates the
executable program that can run.
                
4. 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.
                  
5. 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.
             
6. 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++.               
                          
7. Objective-C 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.
          
8. 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.  
  
9. 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.
                             
10. 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.
                
11. 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.
            
12. 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.
                        
13. 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. 
                               
14. Objective-c memory management: retain and release
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. 
                    
15. 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. 
            
16. 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.
                 
17. 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 this Objective C Tutorial we will provide you step-by-step information in detail. You will find this object c
tutorial very useful.
Objective C Tutorial
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.

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

“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.

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

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
In this section you will learn how to use Objective C on Windows machine. We will download and install Objective
C Windows compiler.

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
fromhttp://www.gnustep.org/experience/Windows.html.
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.
I this section we will show you how to compile and run Objective C program on Mac machine.

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!

 
In this section we will show you how to compile Objective C program on windows and Max OS x machine.

Compiling Objective C
In this section we will show you how to compile Objective C program on windows and Max
OS x machine. Compiling Objective C program is necessary as it generates the executable
program that can run.
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

You can see output of the program…


Here in this section we will know about the keywords used in objective-C language.
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.
ends the declaration, definition,
@end
category or protocol.

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


Directive Definition
Limits the scope of an instance variable to
@private
the class that declares it.
Limits instance variable scope to declaring
@protected
and inheriting classes.
Removes restrictions on the scope of
@public
instance variables.
Exception handling directives.
Directive Definition
Defines a block within which exceptions can
@try
be thrown.
@throw Throws an exception object.
Catches an exception thrown within the
@catch
preceding @try block.
A block of code that is executed whether
@finally exceptions were thrown or not in a @try
block.
Directive used for particular purpose.
Directive Definition
Declares the names of classes
@class
defined elsewhere.
It returns the compiled selector
@selector(method_name)
that identifies method_name.
Returns the protocol_name
protocol (an instance of the
Protocol class). (@protocol is
@protocol(protocol_name)
also valid without
(protocol_name) for forward
declarations.)
Yields a character string that
@encode(type_spec) encodes the type structure of
type_spec.
Defines a constant NSString
object in the current module
and
@"string"
initializes the object with the
specified 7-bit ASCII-encoded
string.
Defines a constant NSString
object in the currentmodule.
The string
@"string1" @"string2" ...
created is the result of
@"stringN"
concatenating the strings
specified in the two
directives.
Defines a block of code that
must be executed only by one
@synchronized()
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.


 Like C and C++ it is used to include a file but it doesn't include more than
#import
once.

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 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 in Objective-C

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. */

Because of objective-C is the extension of ANSI-C and it follows an object oriented approach so provides classes
and objects.
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<Foundation/NSObje
#import<headerFile
ct.h>
.h>
@interface
@interface
ClassName:SuperCla
MyClass:NSObject{
ss {
int a;
variable
int b;
daclaration;
}
variable
-(void) setvara :
daclaration;
(int) x;
}
-(void) setvarb :
method
(int) y;
declaration;
-(int) add;
method
@end
declaration;
@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-C 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 :
21

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<Foundation/NSObje
ct.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/NSObj
ect.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.m

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

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

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”. 

Figure: Flow of Exception handling in Objective-C


/*--------------------------------------------------------------------------------------------------*/

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
"FirstClass.h"
@implementatio
n FirstClass
#import<Foundation/NSObject.     -
h> (void)setNum1 :
@interface
FirstClass:NSObject {
(int) x {
}         num1 = x;
int num1;        
-(void)setNum1 :(int) x; printf("num1 is :
-(int)getNum1; %d \n", num1);
@end
    }
      -(int)getNum1
{
         return
num1;
    }
@end

This is code of derived class.


SecondClass.h                                                  SecondClass.m

#import #import "SecondClass.h"


"FirstClass.m" #import "FirstClass.h"
@implementation
SecondClass
-(id) init {
self = [super init];
@interface return self;
SecondClass: }
FirstClass { -(void)setNum2 :(int) y
int num2 ; {
} num2 = y ;
-(void)setNum2 : printf("num2 is : %d
(int) y; \n", num2);
-(int)mul; }
@end -(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: is object a descendent or member of
classObj classObj
-(BOOL) isMemberOfClass:
is object a member of classObj
classObj
-(BOOL) does the object have a method named
respondsToSelector: selector specifiec by the selector
+(BOOL) does an object created by this class
instancesRespondToSelector: have the ability to respond to the
selector specified selector
-(id) performSelector: invoke the specified selector on the
selector object

Example: 

FirstClass.h                                                 FirstClass.m

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

SecondClass.h                                                  SecondClass.m

#import
"SecondClass.h
"
#import<Foundation/NSObject. @implementatio
h> n SecondClass
@interface -(void)sShow {
SecondClass:NSObject
-(void)sShow; printf("This
@end 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
/*------------------------------------------------------------------------------------------------------*/

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?
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
"MyClass.h"
#import<Foundation/NSObject.h>
@implementation
@interface MyClass:NSObject
MyClass
// This is MyClass
// This is
declaration.
MyClass
@end
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
/*----------------------------------------------------------------------------------------------------*/

When an object contains another objects so before deallocation programmer needs to release all those objects.
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;
}
/*------------------------------------------------------------------------------------------------------------------*/

When programmer wants to add some more functionality to the class, typically extend the class.
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 #import"BaseClass.h"
>
@interface BaseClass :
NSObject { @implementation
int num1, num2; BaseClass
}     -(void)set :(int) x and:
-(void)set :(int) x and: (int) y {
(int) y;
-(int)add;
        num1 = x;
-(int)sub;         num2 = y;
@end     }
    -(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"SubClass.h"
@implementation
 
#import"BaseClass.h"
BaseClass(BaseClass)  
@interface
-(void)show:(int)x {
BaseClass(Category)
-(void)show:(int)x;
printf("Result is :  
%d \n",x);
@end  
}
  @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
/*--------------------------------------------------------------------------------------------------------*/

Posing is similar to category but it works a little bit different with the category.
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 #import"BaseClass.h"
> @implementation BaseClass
   
@interface BaseClass : -(void)set :(int) x  
NSObject { and: (int) y {
int num1, num2; num1 = x;  
} num2 = y;
-(void)set :(int) x and: }  
(int) y; -(int)add {
-(int)add; return num1+num2;
 
-(int)sub; }     
-(void)show:(int)x; -(int)sub {
@end if(num1>num2){  
return num1-
  num2;  
}
 
else
return num2-  
num1;
SubClass.h
}    SubClass.m
-(void)show:(int)x {
#import"BaseClass.h"   #import"SubClass.h"
printf("Base
@interface class:
SubClass   @implementation SubClass
result : %d \n",x);
BaseClass -(void)show:(int)x {
} -(void)show:(int)x;  
printf("Sub class result :
@end@end   %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

You might also like