Objective C Notes

13
6/10/2015 Objective C Notes file:///G:/c/Objective%20C%20Notes.htm 1/13 Objective C Notes Wednesday, September 26, 2012 OBJECTIVE-C NOTES 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? http://iosbricks.blogspot.com IOS Dev. 2012 (1) September (1) OBJECTIVE-C NOTES Blog Archive venkatesh pachigulla View my complete profile About Me 0 Share More Next Blog» Create Blog Sign In

description

objectivec

Transcript of Objective C Notes

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 1/13

    Objective C Notes

    Wednesday, September 26, 2012

    OBJECTIVE-C NOTES

    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?

    http://iosbricks.blogspot.com

    IOS Dev.

    2012 (1)

    September (1)

    OBJECTIVE-C NOTES

    Blog Archive

    venkatesh pachigulla

    View my complete profile

    About Me

    0Share More Next Blog Create Blog Sign In

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 2/13

    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 functionalists 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-Chas dynamism has two major benefits:

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

    interface.

    2. It enables to development of sophisticated development tools. An interface to the run time

    system gives a facility to access the information about application at rum time this makes possible

    to monitor objective-C application.

    Objective C Hello World Example

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

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 3/13

    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.

    @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 to the class that declares

    it.

    @protected Limits instance variable scope to declaring and inheriting classes.

    @public Removes restrictions on the scope of instance variables.

    Exception handling directives.

    Directive Definition

    @try Defines a block within which exceptions can be thrown.

    @throw Throws an exception object.

    @catch Catches an exception thrown within the preceding @try block.

    @finallyA block of code that is executed whether exceptions were thrown or not

    in a @try block.

    Directive used for particular purpose.

    Directive Definition

    @class Declares the names of classes defined elsewhere.

    @selector(method_name) It returns the compiled selector that identifies method_name.

    @protocol(protocol_name)

    Returns the protocol_name protocol (an instance of the

    Protocol class). (@protocol is also valid without

    (protocol_name) for forward

    declarations.)

    @encode(type_spec)Yields a character string that encodes the type structure of

    type_spec.

    @"string"

    Defines a constant NSString object in the current module and

    initializes the object with the specified 7-bit ASCII-encoded

    string.

    @"string1" @"string2" ...

    @"stringN"

    Defines a constant NSString object in the currentmodule. The

    string

    created is the result of concatenating the strings specified in

    the two

    directives.

    @synchronized()

    Defines a block of code that must be executed only by one

    thread

    at a time.

    Some keywords of Objective-C are not reserved outside. These are..

    in out inout bycopy

    byref oneway

    Keyword for memory management in Objective-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 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.

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 4/13

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

    Message Expressions and 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. */

    Class and Method declaration and definitions

    Because of objective-C is the extension of ANSI-C and it follows an object oriented approach so

    provides classes and objects. The way to declare and define classes and creation of object is little

    bit different from C and C++.

    To declare a new class objective-C uses @interface directive.

    Declaration of a simple class: MyClass.h

    #import"SuperClass.h"

    #import

    @interface ClassName:SuperClass {

    variable declaration;

    variable declaration;

    }

    method declaration;

    method declaration;

    @end

    #import

    @interface MyClass:NSObject{

    int a;

    int b;

    }

    -(void) setvara : (int) x;

    -(void) setvarb : (int) y;

    -(int) add;

    @end

    Definition of declared class: MyClass.m

    #import

    #import"MyClass.h"

    @implementation MyClass

    -(void) setvara :(int) x{

    a=x;

    }

    -(void) setvarb :(int) y{

    b=y;

    }

    -(int) add{

    return a+b;

    }

    @end

    Piecing it together

    main.m

    #import

    #import"MyClass.m"

    int main(){

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 5/13

    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

    @interface MyClass:NSObject{

    }

    // declare method for more than one parameter

    -(int) sum: (int) a andb: (int) b andc:(int)c;

    @end

    MyClass.m//Syntax

    #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 : 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

    @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];

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 6/13

    if(self) {

    a=x;

    b=y;

    return self;

    }

    }

    -(void) sum {

    printf("Sum is : %d",a+b);

    }

    @end

    MyClassMain.m

    #import

    #import"MyClass.m"

    int main(){

    // use constructor

    MyClass *class = [[MyClass alloc] set : 10 andb : 12];

    [class sum];

    [class release];

    return ;

    }

    Output:

    Sum is : 22

    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

    @interface MyClass:NSObject {

    @private

    int a;

    int b;

    }

    -(void) set:(int) x andb:(int) y;

    -(void) sum;

    -(void)show;

    @end

    MyClass.m

    #import

    #import"MyClass.h"

    @implementation MyClass

    -(void) set:(int) x andb:(int) y {

    a=x;

    b=y;

    }

    -(void) sum {

    printf("Sum is : %d \n",a+b);

    }

    -(void)show{

    printf("value of a is : %d \n",a);

    printf("value of b is : %d \n",b);

    }

    @end

    MyClassMain.m

    #import

    #import"MyClass.m"

    int main(){

    MyClass *class1 = [[MyClass alloc] init];

    MyClass *class2 = [[MyClass alloc] init];

    [class1 set: 10 andb :12];

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 7/13

    [class1 show];

    [class1 sum];

    // This is invalid statement because variable a is private.

    // class2->a = 10;

    class2->b = 15;

    [class2 show];

    [class2 sum];

    [class1 release];

    [class1 release];

    return ;

    }

    Output:

    value of a is : 10

    value of b is : 12

    Sum is : 22

    value of a is : 0

    value of b is : 15

    Sum is : 15

    Class level access

    Objective-C provides facility of class level access. In the examples given above we have used '-'

    sign before method, '-' means instance level access. Now we will see how to define method that

    can be access on class level.

    MyClass.h

    #import

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

    Objective-C Inheritance

    SecondClass.h

    -(void)setNum1 :(int) x;

    -(int)getNum1;

    #import "FirstClass.h"

    @implementation FirstClass

    -(void)setNum1 :(int) x {

    num1 = x;

    printf("num1 is : %d \n", num1);

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

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 8/13

    @end }

    -(int)getNum1 {

    return num1;

    }

    @end

    This is code of derived class.

    SecondClass.m

    #import "FirstClass.m"

    @interface SecondClass:

    FirstClass {

    int num2 ;

    }

    -(void)setNum2 :(int) y;

    -(int)mul;

    @end

    #import "SecondClass.h"

    #import "FirstClass.h"

    @implementation SecondClass

    -(id) init {

    self = [super init];

    return self;

    }

    -(void)setNum2 :(int) y {

    num2 = y ;

    printf("num2 is :

    %d \n", num2);

    }

    -(int)mul {

    return num2*[self getNum1];

    }

    @end

    This is code of main class.

    main.m

    #import "SecondClass.m"

    #import

    int main() {

    FirstClass *obj1 = [[FirstClass alloc] init];

    SecondClass *obj2 = [[SecondClass alloc] init];

    [obj1 setNum1 : 10 ];

    [obj2 setNum2 : 15 ];

    printf("Multiplication Result : %d \n",[obj2 mul]);

    return 0;

    }

    Output:

    num1 is : 10

    num2 is : 15

    Multiplication Result : 150

    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:

    classObjis object a descendent or member of classObj

    -(BOOL) isMemberOfClass:

    classObjis object a member of classObj

    -(BOOL) respondsToSelector:

    selector

    does the object have a method named specifiec by the

    selector

    +(BOOL)

    instancesRespondToSelector:

    selector

    does an object created by this class have the ability to

    respond to the specified selector

    -(id) performSelector: selector invoke the specified selector on the object

    Example:

    FirstClass.h FirstClass.m

    #import

    @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

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 9/13

    #import

    @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

    int main() {

    FirstClass *fClassObj = [[FirstClass alloc] init];

    SecondClass *sClassObj = [[SecondClass alloc] init];

    /* some methods to work with dynamic types */

    // -(BOOL) isKindOfClass: classObj ----------- true

    if ( [fClassObj isKindOfClass: [FirstClass class]] == YES ) {

    printf( "fClassObj is kind of FirstClass.\n" );

    }

    // -(BOOL) isKindOfClass: classObj ----------- false

    if ( [fClassObj isKindOfClass: [SecondClass class]] == YES ) {

    printf( "fClassObj is kind of SecondClass.\n" );

    }

    else

    printf( "fClassObj is not kind of SecondClass.\n" );

    // -(BOOL) isMemberOfClass: classObj ----------- true

    if ( [fClassObj isMemberOfClass: [FirstClass class]] == YES ) {

    printf( "fClassObj is member of FirstClass.\n" );

    }

    // -(BOOL) isMemberOfClass: classObj ----------- false

    if ( [sClassObj isMemberOfClass: [FirstClass class]] == YES ) {

    printf( "sClassObj is member of FirstClass.\n" );

    }

    else

    printf( "sClassObj is not member of FirstClass.\n" );

    // -(BOOL) respondsToSelector: selector ----- true

    if ( [fClassObj respondsToSelector: @selector(fShow)] == YES ) {

    printf( "fClassObj responds to fShow method\n" );

    }

    // -(BOOL) respondsToSelector: selector ----- false

    if ( [sClassObj respondsToSelector: @selector(fShow)] == YES ) {

    printf( "sClassObj responds to fShow method\n" );

    }

    else

    printf( "sClassObj does'nt respond to fShow method\n" );

    // release memory allocated for the objects

    [fClassObj release];

    [sClassObj release];

    return 0;

    }

    Output:

    fClassObj is kind of FirstClass.

    fClassObj is not kind of SecondClass.

    fClassObj is member of FirstClass.

    sClassObj is not member of FirstClass.

    fClassObj responds to fShow method

    sClassObj does'nt respond to fShow method

    Objective-c memory management: retain and release

    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" );

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 10/13

    [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

    @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]; 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

    #import

    @interface Student: NSObject {

    NSString *fName;

    NSString *lName;

    NSString *email;

    }

    -(void) set: (NSString*) f last: (NSString*)l email:(NSString*)e;

    -(void) setFirst: (NSString*) f;

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 11/13

    -(void) setLast: (NSString*) l;

    -(void) setEmail: (NSString*) e;

    -(NSString*) firstName;

    -(NSString*) lastName;

    -(NSString*) email;

    -(void) print;

    @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"];

    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;

    }

    Categories

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 12/13

    Home

    Subscribe to: Posts (Atom)

    Posted by venkatesh pachigulla at 2:59 AM No comments:

    Labels: Objective c, objective c document, objective c notes, objective c pdf, objective c tutorial, objective c tutorial

    apple, objective c tutorial for beginners, objective c tutorial iphone

    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

    @interface BaseClass : NSObject {

    int num1, num2;

    }

    -(void)set :(int) x and: (int) y;

    -(int)add;

    -(int)sub;

    @end

    #import"BaseClass.h"

    @implementation

    BaseClass

    -(void)set :(int) x and: (int) y {

    num1 = x;

    num2 = y;

    }

    -(int)add {

    return num1+num2;

    }

    -(int)sub {

    if(num1>num2){

    return num1-num2;

    }

    else

    return num2-num1;

    }

    @end

    This is code of sub class that is used to add method in the primary class.

    SubClass.h SubClass.m

    #import"BaseClass.h"

    @interface BaseClass(Category)

    -(void)show:(int)x;

    @end

    #import"SubClass.h"

    @implementation BaseClass(BaseClass)

    -(void)show:(int)x {

    printf("Result is : %d \n",x);

    }

    @end

    main.m

    #import"BaseClass.m"

    #import"SubClass.m"

    #import

    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

    tags:Objective c, objective c document, objective c notes, objective c tutorial, objective c tutorial

    pdf, objective c tutorial for beginners, iphone development tutorial, objective c tutorial iphone,

    objective c tutorial apple, objective c pdf,

    Recommend this on Google

    Simple template. Powered by Blogger.

  • 6/10/2015 Objective C Notes

    file:///G:/c/Objective%20C%20Notes.htm 13/13