8/8/2019 Objective C Programming Language
1/32
Objective C is a programming language, which is sleeted by Apple for developing theapplication 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. Youwill 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 TutorialAbout the Objective C tutorial presented here. In this complete guide of Objective C youwill be learning the programming concepts by doing the coding. We follow the learn by
doing concepts.
2. Objective C IntroductionThis section provides you the basic introduction about Objective C programming
language. Objective C is very old programming language and it was designed anddeveloped 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 andiPhone.
1. Objective C Hello World ExampleIn this section I will show you how to develop Objective C Hello World program.
Objective C on WindowsIn 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 canbe used to compile the Objective C program.
2. Objective C on MacI this section we will show you how to compile and run Objective C program on Macmachine.
3. Compiling Objective CIn this section we will show you how to compile Objective C program on windows andMax OS x machine. Compiling Objective C program is necessary as it generates theexecutable program that can run.
4. Objective-C keywordsIn 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.
8/8/2019 Objective C Programming Language
2/32
5. Message Expressions and commentsLike 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 insquare brackets.
6.
Class and Method declaration and definitionsBecause of objective-C is the extension of ANSI-C and it follows an object orientedapproach 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 parameterObjective-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. ConstructorsObjective-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 tothe 'self' keyword, actually 'self' plays same role as this keyword in C++ and Java.
9. Access Modifiers and Garbage CollectionPreviously it was a requirement to allocate and release memory manually to assist withthis problem it provides a reference-counting memory management system through retain
and release keywords.
10.Class level accessObjective-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 todefine method that can be access on class level.
11.Exception handling in Objective-CObjective-C provide exception handling to handle exceptional conditions so that code canbe 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 InheritanceObjective-C enables programmer to inherit common methods and properties from other
class, known as inheritance. Class from methods and properties are inherited known asBase Class and class that inherits known as Derived Class.
13.Dynamic Types in Objective-CObjective-C provides many methods to work with dynamic types. With these methodsprogrammer can check that object is of the given class or not, given method is member of
the given class or not etc.
8/8/2019 Objective C Programming Language
3/32
14.Objective-c memory management: retain and releaseObjective-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 objecthas.
15.Objective-c
DeallocWhen 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.CategoriesWhen 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 providescategories to achieve this.
17.PosingPosing is similar to category but it works a little bit different with the category. It enableprogrammers 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.
8/8/2019 Objective C Programming Language
4/32
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 tofollow 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 priorprogramming 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 willfind 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 andstart 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 tolearn 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 towardslearn 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 Fundamentals2. Understanding the Objective C OOPs concepts3. Memory management in Objective C4. Objective C Foundation framework5. Files and I/O operations6. 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 yourdevelopment environment and then test few programs. Once you are able to run the firstprogram, 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 andtesting the application
8/8/2019 Objective C Programming Language
5/32
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 oldprogramming 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-orientedprogramming. 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 orientedcapabilities.
Objective C is simple and very intuitive programming language that makes the ObjectOriented 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 objectoriented programming capabilities just like C and all these things are done in very simple and
straightforward way.
Most of the programming language provides:
y A library of Objectsy Necessary development toolsy OOP' support and related libraries
Objective C provides all the above components. You can use Objective C to develop fullfledge 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 thesedevices.
Like an object oriented language Objective C revolves around objects. It has three parts:
1. inter- faceInterface 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 ofsuffixed .m. It is a definition of a class.
3. Instantiation
8/8/2019 Objective C Programming Language
6/32
After declaring and defining class we can be instantiated by allocating memory to thenew object of the class.
In a nutshell Objective C is:
y Extension of C programming languagey Simple yet powerful object oriented programming languagey 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. Someare 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
8/8/2019 Objective C Programming Language
7/32
postponed until the program is running.
Objective-Cs 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 WorldIn 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
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 windowsmachine 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 ObjectiveC Windows compiler.
Objective C on WindowsIn this section you will learn how to use Objective C on Windows machine. We will downloadand install Objective C Windows compiler. On windows GNU C compiler can be used to
compile the Objective C program.
Objective C Compiler for Windows
8/8/2019 Objective C Programming Language
8/32
The GNUstep windows installer can be downloaded and installed on the windows system tocompile 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 downloadedfromhttp://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 theGNUsetup 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 Cprogram 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 MacI this section we will show you how to compile and run Objective C program on Macmachine.
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
8/8/2019 Objective C Programming Language
9/32
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 CIn this section we will show you how to compile Objective C program on windows and MaxOS 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 followingcommand.
$ cd c:/objectiveC
To compile program run the following command
$ gcc -o hello hello.m
8/8/2019 Objective C Programming Language
10/32
This command will create a executable file of given name (here 'hello').
To run the program
$./hello
You can see output of the program
8/8/2019 Objective C Programming Language
11/32
Here in this section we will know about the keywords used in objective-C language.
Objective-C keywordsHere 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.
@implementationused to define a class or category.
@protocol used to declare a formal protocol.
@endends the declaration, definition,category or protocol.
Directive used to specify the visibility of the instance.Default is @protected.
Directive Definition
@privateLimits the scope of an instance variable tothe class that declares it.
@protectedLimits instance variable scope to declaring
and inheriting classes.
@publicRemoves restrictions on the scope of
instance variables.
Exception handling directives.
Directive Definition
@tryDefines 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 @tryblock.
Directive used for particular purpose.
Directive Definition
8/8/2019 Objective C Programming Language
12/32
@classDeclares the names of classesdefined elsewhere.
@selector(method_name)It returns the compiled selector
that identifies method_name.
@protocol(protocol_name)
Returns the protocol_nameprotocol (an instance of the
Protocol class). (@protocol isalso valid without
(protocol_name) for forwarddeclarations.)
@encode(type_spec)
Yields a character string thatencodes the type structure of
type_spec.
@"string"
Defines a constant NSStringobject in the current module
andinitializes the object with the
specified 7-bit ASCII-encodedstring.
@"string1" @"string2" ...
@"stringN"
Defines a constant NSStringobject in the currentmodule.
The stringcreated is the result of
concatenating the stringsspecified in the two
directives.
@synchronized()
Defines a block of code thatmust be executed only by one
threadat 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-CThese 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
8/8/2019 Objective C Programming Language
13/32
value either TRUE or FALSE.
2.'super' and 'self' can be treated as keywords but self is a hidden parameter to each methodand 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.
#importLike C and C++ it is used to include a file but it doesn't include more than
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 commentsLike 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 squarebrackets.
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 variableself)
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.
CommentsLike 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
8/8/2019 Objective C Programming Language
14/32
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;
}
methoddeclaration;
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];
8/8/2019 Objective C Programming Language
15/32
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
@interface MyClass:NSObject{
}
// declare method for more than
one parameter
-(int) sum: (int) a andb: (int)
b andc:(int)c;
@end
MyClass.m#import
#import"MyClass.h"
@implementation MyClass
-(int) sum: (int) a andb: (int)
b andc:(int)c;{return a+b+c;
}
@end
MyClass.m#import
#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 :
8/8/2019 Objective C Programming Language
16/32
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
@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(){
8/8/2019 Objective C Programming Language
17/32
// 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 andrelease 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'sability 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
8/8/2019 Objective C Programming Language
18/32
#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
8/8/2019 Objective C Programming Language
19/32
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 methodthat can be access on class level.
MyClass.h
#import@interface MyClass:NSObject {
}
-(void)instanceShow;
+(void)classShow;
@end
MyClass.m
#import
#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
#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 onclass 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 andit calls for every class so it is the better place to define class level variable
/*----------------------------------------------*/
Exception handling in Objective-C
8/8/2019 Objective C Programming Language
20/32
Objective-C provide exception handling to handle exceptional conditions so that code can beeasier 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 codethat 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 Classand 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 belowVehicle is the base class and both Car and Bike are derived classes so that these classes can
use methods and properties of Vehicle class.
8/8/2019 Objective C Programming Language
21/32
Example:
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{
returnnum1;
}@end
This is code of derived class.
SecondClass.h SecondClass.m
#import #import "SecondClass.h"
8/8/2019 Objective C Programming Language
22/32
"FirstClass.m"
@interface
SecondClass:
FirstClass {
int num2 ;
}
-(void)setNum2:(int) y;
-(int)mul;
@end
#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
/*----------------------------------------------------------------------------------------------------*/
Dynamic Types in Objective-C
Objective-C provides many methods to work with dynamic types. With these methodsprogrammer 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 briefdescription.....
8/8/2019 Objective C Programming Language
23/32
Method Description
-(BOOL) isKindOfClass:
classObj
is object a descendent or member ofclassObj
-(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 thespecified selector
-(id) performSelector:
selector
invoke the specified selector on the
object
Example:
FirstClass.h FirstClass.m
#import
@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@interface
SecondClass:NSObject
-(void)sShow;
@end
#import
"SecondClass.h"
@implementationSecondClass
-(void)sShow {
printf("This
is first
class.");
}
@end
main.m
8/8/2019 Objective C Programming Language
24/32
#import "FirstClass.m"
#import "SecondClass.m"
#import
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 ) {
8/8/2019 Objective C Programming Language
25/32
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. Programmercan 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 internalcounter 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. Whencounter 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" );
8/8/2019 Objective C Programming Language
26/32
[super dealloc];
}
retainCount: retain count method is used to show the internal count of the given object sothat programmer can easily increment and decrement the counter as per requirement.
Example:
MyClass.h MyClass.m
#import
@interface MyClass:NSObject
// This is MyClass
declaration.
@end
#import
"MyClass.h"
@implementation
MyClass
// This is
MyClass
definition.
@end
main.m
#import "MyClass.m"
#import
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];
8/8/2019 Objective C Programming Language
27/32
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 releaseall 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 stringvalues 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 objectsfirst.
Example :
Student.h
#import
#import
@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;
8/8/2019 Objective C Programming Language
28/32
@end
Student.m
#import "Student.h"
#import
@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
#import
int main( int argc, const char *argv[] ) {
NSString *fName =[[NSString alloc]
initWithCString: "Mahendra"];
8/8/2019 Objective C Programming Language
29/32
NSString *lName = [[NSString alloc]
initWithCString: "Singh"];
NSString *email = [[NSString alloc]
initWithCString: "[email protected]"];
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 theclass. 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 classeswithout extending them.
In the example given below we have a class BaseClass that has some methods and the secondclass 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
@interface BaseClass :
NSObject {
int num1, num2;
}
-(void)set :(int) x and:(int) y;
-(int)add;
-(int)sub;
@end
#import"BaseClass.h"
@implementationBaseClass
-(void)set :(int) x and:(int) y {
num1 = x;num2 = y;
}-(int)add {
return num1+num2;}
8/8/2019 Objective C Programming Language
30/32
-(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.
main.m
#import"BaseClass.m"
#import"SubClass.m"
#import
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 enableprogrammers 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
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
8/8/2019 Objective C Programming Language
31/32
object of base class, show method will show the output according to the base class but afterposing it will display output from show method defined in sub class.
Example:
main.m
#import"BaseClass.m"
#import"SubClass.m"
#import
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
BaseClass.h BaseClass.m#import
@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
8/8/2019 Objective C Programming Language
32/32
[obj1 release];
[obj2 release];
return 0;
}
Output:
Base class result: 18
Base class result
: 2
Sub class result :
17
Sub class result :
5