Objective C Notes
Objective C Notes
Objective C Notes
Share
More
Next Blog
Create Blog
Sign In
Objective C Notes
Wednesday, Septem ber 26, 2012
IOS Dev.
OBJECTIVE-C NOTES
http://iosbricks.blogspot.com
Blog Archive
2012 (1)
September (1)
OBJECTIVE-C NOTES
About Me
venkatesh pachigulla
View my complete profile
OBJECTIVE-C
PREPARED BY VENKATESH-MAHATHI SOFTWARE
Objective C is a programming language, which is selected by Apple for developing the
application for iPhone, iPad 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 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.
Why Objective C?
file:///G:/c/Objective%20C%20Notes.htm
1/13
6/10/2015
Objective C Notes
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
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
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!
Compiling Objective C
Go to the directory where hello.m example program is saved. You can use the following
commands as shown below
Objective-C keywords
Objective-C is a superset of C language, so program written in c and C++ should compile
file:///G:/c/Objective%20C%20Notes.htm
2/13
6/10/2015
Objective C Notes
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
@implementation
@protocol
@end
Definition
@private
@protected
@public
Definition
@try
@throw
@catch
@finally
Definition
@class
@selector(method_name)
@protocol(protocol_name)
@encode(type_spec)
@"string"
@synchronized()
out
byref
oneway
inout
bycopy
alloc
retain
release
autorelease
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.
file:///G:/c/Objective%20C%20Notes.htm
3/13
6/10/2015
Objective C Notes
Preprocessor Directives
The preprocessor directives are special notations:
Directive
//
#import
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
once.
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++.
To declare a new class objective-C uses @interface directive.
Declaration of a simple class: MyClass.h
#import<Foundation/NSObject.h>
#import"SuperClass.h"
#import<headerFile.h>
@interface MyClass:NSObject{
@interface ClassName:SuperClass {
int a;
variable declaration;
int b;
variable declaration;
}
}
-(void) setvara : (int) x;
method declaration;
-(void) setvarb : (int) y;
method declaration;
-(int) add;
@end
@end
#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(){
file:///G:/c/Objective%20C%20Notes.htm
4/13
6/10/2015
Objective C Notes
MyClass *class = [[MyClass alloc]init];
[class setvara : 5];
[class setvarb : 6];
printf("Sum is : %d",[class add]);
[class release];
return ;
}
MyClass.m//Syntax
#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
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/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];
file:///G:/c/Objective%20C%20Notes.htm
5/13
6/10/2015
Objective C Notes
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];
file:///G:/c/Objective%20C%20Notes.htm
6/13
6/10/2015
Objective C Notes
[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
MyClass.h
#import<Foundation/NSObject.h>
@interface MyClass:NSObject {
MyClass.m
#import<stdio.h>
#import"MyClass.h"
@implementation MyClass
-(void)instanceShow {
printf("This is instance
level method.\n");
}
}
-(void)instanceShow;
+(void)classShow;
@end
MyClassMain.m
#import<stdio.h>
#import"MyClass.m"
int main(){
MyClass *instance = [
[MyClass alloc]init];
[instance instanceShow];
[MyClass classShow];
[instance release];
return ;
}
+(void)classShow {
printf("This is class
level method.");
}
@end
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 -f obj-exceptions flag is turned on.
These are four compiler directives that are used for exception handling1. @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
SecondClass.h
#import "FirstClass.h"
-(void)setNum1 :(int) x;
-(int)getNum1;
file:///G:/c/Objective%20C%20Notes.htm
@implementation FirstClass
-(void)setNum1 :(int) x {
num1 = x;
printf("num1 is : %d \n", num1);
7/13
6/10/2015
Objective C Notes
@end
}
-(int)getNum1 {
return num1;
}
@end
SecondClass.m
#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
#import "FirstClass.m"
@interface SecondClass:
FirstClass {
int num2 ;
}
-(void)setNum2 :(int) y;
-(int)mul;
@end
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
Description
-(BOOL) isKindOfClass:
classObj
-(BOOL) isMemberOfClass:
classObj
-(BOOL) respondsToSelector:
selector
+(BOOL)
instancesRespondToSelector:
selector
Example:
FirstClass.h FirstClass.m
#import "FirstClass.h"
#import<Foundation/NSObject.h>
@implementation FirstClass
@interface FirstClass:NSObject
-(void)fShow {
-(void)fShow ;
printf("This is first class.");
+(void)classShow ;
}
@end
+(void)classShow {
}
@end
SecondClass.h SecondClass.m
file:///G:/c/Objective%20C%20Notes.htm
8/13
6/10/2015
Objective C Notes
#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
file:///G:/c/Objective%20C%20Notes.htm
9/13
6/10/2015
Objective C Notes
[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>
#import "MyClass.h"
@interface MyClass:NSObject
@implementation MyClass
// This is MyClass declaration.
// This is MyClass definition.
@end
@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;
file:///G:/c/Objective%20C%20Notes.htm
10/13
6/10/2015
Objective C Notes
-(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
file:///G:/c/Objective%20C%20Notes.htm
11/13
6/10/2015
Objective C Notes
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"
#import"SubClass.h"
@interface BaseClass(Category) @implementation BaseClass(BaseClass)
-(void)show:(int)x;
-(void)show:(int)x {
@end
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:
Home
Subscribe to: Posts (Atom)
file:///G:/c/Objective%20C%20Notes.htm
12/13
6/10/2015
file:///G:/c/Objective%20C%20Notes.htm
Objective C Notes
13/13