oops objectivec1

Upload: guillermo-oswaldo

Post on 06-Apr-2018

235 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 OOPS Objectivec1

    1/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    NOTICE:

    You DO NOT Have the RightTo Reprint OR Resell This Report

    In Addition, You MAY NOT Give Away,

    Sell, OR Share the Content Herein If you obtained this ebook course from anywhere other than

    www.EDUmobile.ORG you have a pirated copy.

    Copyright 2009 EDUmobile.ORG - ALL RIGHTS RESERVED.

    No part of this ebook and mobile course may be reproduced or transmitted in any formwhatsoever, electronic, or mechanical, including photocopying, recording, or by anyinformational storage or retrieval system without expressed written, dated, and signedpermission from the author.

    DISCLAIMER AND/OR LEGAL NOTICES:

    The information presented herein represents the view of the authors as of the date ofpublication. Due to the rate with which conditions change, the authors reserve theirright to alter and update his opinions based on the new conditions. This report is forinformational purposes only. The authors do not accept any responsibilities for anyliabilities resulting from the use of this information. While every attempt has been madeto verify the information provided here, the author cannot assume any responsibilityfor errors or omissions.

  • 8/3/2019 OOPS Objectivec1

    2/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    Object oriented programming with Objective C

    1. Instances and Methods

    A unique occurrence of a class is an instance, and the actions that areperformed on the instance are called methods. In some cases, a methodcan be applied to an instance of the class or to the class itself.

    Applying a method to an object can affect the state of that object. If yourmethod is to "paint your Rectangle " after that method is performed yourRectangle will become colored. The method will have affected the stateof the object of the Rectangle class.

    The key concepts here are that objects are unique representations from aclass, and each object contains some information (data) that is typicallyprivate to that object. The methods provide the means of accessing andchanging that data.

    The Objective-C programming language has the following particularsyntax for applying methods to classes and instances:

    [ ClassOrInstance method ];

    In this syntax, a left bracket is followed by the name of a class or instanceof that class, which is followed by one or more spaces, which is followedby the method you want to perform. Finally, it is closed off with a rightbracket and a terminating semicolon.

    Let us look at the example

    bigRectangle = [Rectangle new]; get a new Rectangle

    You send a message to the Rectangle class (the receiver of the message)asking it to give you a new rectangle. The resulting object (whichrepresents your unique rectangle), is then stored in the variable big

  • 8/3/2019 OOPS Objectivec1

    3/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    Rectangle . From now on, bigRectangle can be used to refer to your instanceof the rectangle, which you got from the factory.

    The method new is called a factory or class method .

    2. A Sample Example

    // Program to work with point class version

    #import

    #import

    //------- @interface section -------

    @interface Point: Object

    {

    int abscissa;

    int ordinate;

    }

    -(void) print;

    -(void) setX: (int) x;

    -(void) setY: (int) y;

  • 8/3/2019 OOPS Objectivec1

    4/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    @end

    //------- @implementation section -------

    @implementation Point;

    -(void) print

    {

    printf (" %i/%i ",abscissa , ordinate);

    }

    -(void) setX: (int) x

    {

    abscissa = x;

    }

    -(void) setY: (int) y

    {

    ordinate = y;

    }

    @end

  • 8/3/2019 OOPS Objectivec1

    5/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    //------- program section -------

    int main (int argc, char *argv[])

    {

    Point *myPoint;

    // Create an instance of a Fraction

    myPoint = [Point alloc];

    myPoint = [myPoint init];

    // Set point to 1/4

    [myPoint setX: 1];

    [myPoint setY: 4];

    // Display the point using the print method

    printf ("The value of myPoint is:");

    [myPoint print];

    printf ("\n");

    [myPoint free];

    return 0;

    }

    The program above is a simple program written in objective C. It createsa class Point and you can relate easily with the program above islogically divided into

  • 8/3/2019 OOPS Objectivec1

    6/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    1) Interface It contains the declaration.

    2) Implementation It contains the implementation.

    3) Program It contains the usage section.

    3. Important Data type

    id

    The id data type is used to store an object of any type. It is in a sense ageneric object type. For example, the line

    id number;

    declares number to be a variable of type id . Methods can be declared toreturn values of type id , like so:

    -(id) newObject: (int) type;

    This declares an instance method called newObject that takes a singleinteger argument called type and returns a value of type id . You shouldnote that id is the default type for return and argument type declarations.So, the following

    +allocInit;declares a class method that returns a value of type id .

    The id type is the basis for very important features in Objective-C knowsas polymorphismand dynamic binding.

  • 8/3/2019 OOPS Objectivec1

    7/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    The other basic data types are not discussed here as the reader isexpected to have a basic knowledge of C. However incase of any queriesplease write to us for clarification.

    4. Separate Interface and Implementation Files

    Typically, a class declaration (that is, the @interface section) is placed in itsown file, called class.h . The definition (that is, the @implementation section)is normally placed in a file of the same name, using the extension .m instead. So, let's put the declaration of the Point class into the file Point.h and the definition into Point.m . A main.m will generally keep the mainfunction. Try to write the Point program written above in separateclasses and compile.

    ///////////////////////////////////////////////Point.h////////////////////////////////////////////

    #import

    //------- @interface section -------

    @interface Point: Object

    {

    int abscissa;

    int ordinate;

    }

    -(void) print;

    -(void) setX: (int) x;

  • 8/3/2019 OOPS Objectivec1

    8/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    -(void) setY: (int) y;

    @end

    ///////////////////////////////////////////////////////////////////////////////////////////////

    //////////////////////////////////////Point.m////////////////////////////////////////////

    #import "Point.h"

    #import

    @implementation Point;

    -(void) print

    {

    printf (" %i/%i ",abscissa , ordinate);

    }

    -(void) setX: (int) x

    {

    abscissa = x;

    }

    -(void) setY: (int) y

    {

    ordinate = y;

    }

  • 8/3/2019 OOPS Objectivec1

    9/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    @end

    /////////////////////////////////////////////////// main.m /////////////////////////////////////////////

    #import "Point.h"

    #import

    int main (int argc, char *argv[])

    {

    Point *myPoint;

    // Create an instance of a Fraction

    myPoint = [Point alloc];

    myPoint = [myPoint init];

    // Set point to 1/4

    [myPoint setX: 1];

    [myPoint setY: 4];

    // Display the point using the print method

    printf ("The value of myPoint is:");

    [myPoint print];

    printf ("\n");

    [myPoint free];

    return 0;

  • 8/3/2019 OOPS Objectivec1

    10/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    }

    //////////////////////////////////////////////////////////////////////////////////////////

    You can also use multiple arguments to a function separated by colon:multiple arguments

    [myPoint setX: 1 andsetY: 3];

    Note: The keyword self can be used to refer to the object that is the

    receiver of the current method.

    5. Returning Objects from methods

    The following example shows how we can return an object from amethod

    -(Point *) add: (Point *) f {

    // To add two points

    // result will store the result of the addition

    Point *result = [[Point alloc] init];int resultX, resultY;

    resultX = (abscissa + [f abscissa]);resultY= (ordinate+ [f ordinate]);

    [result setX: resultX setY: resultY];//It is a new method with multiple parameters

    return result; }The example clearly shows how we can return an object from a method

  • 8/3/2019 OOPS Objectivec1

    11/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    Exercise Please attempt the following and send the same [email protected]

    1) Write an Objective C program to represent complex numbers withfollowing functions

    -(void) setReal: (double) a;-(void) setImaginary: (double) b;-(void) print; // display as a + bi-(double) real;-(double) imaginary;

    2) Write a program that takes an integer keyed in from the terminal andextracts and displays each digit of the integer in English. So, if the usertypes in 932, the program should display the following:

    3) Makes a complex class and write methods for addition, subtraction,multiplication, division and square root.

    Appendix

    Directives used to declare and define classes, categories and protocols:

    Directive Definition

    @interface used to declare of classor interface.

    @implementation used to define a class orcategory.

    @protocol used to declare a formal

    protocol.

    @end ends the declaration,definition, category orprotocol.

  • 8/3/2019 OOPS Objectivec1

    12/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

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

    Directive Definition

    @private Limits the scope of an instancevariable to the class thatdeclares it.

    @protected

    Limits instance variable scope

    to declaring and inheritingclasses.

    @public Removes restrictions on thescope 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 thrownwithin the preceding @try block.

    @finally A block of code that is executedwhether exceptions were thrownor not in a @try block.

    Directive used for particular purpose.

    Directive Definition

    @class

    Declares thenames of classesdefinedelsewhere.

  • 8/3/2019 OOPS Objectivec1

    13/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    @selector(method_name)

    It returns thecompiled selectorthat identifiesmethod_name.

    @protocol(protocol_name)

    Returns theprotocol_nameprotocol (aninstance of theProtocol class).

    (@protocol is alsovalid without(protocol_name)for forwarddeclarations.)

    @encode(type_spec)

    Yields a characterstring thatencodes the typestructure oftype_spec.

    @"string"

    Defines a constantNSString object inthe currentmodule andinitializes theobject with thespecified 7-bitASCII-encodedstring.

    @"string1" @"string2" ...@"stringN"

    Defines a constantNSString object inthecurrentmodule.The stringcreated is theresult of

  • 8/3/2019 OOPS Objectivec1

    14/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    concatenating thestrings specifiedin the twodirectives.

    @synchronized()

    Defines a block ofcode that must beexecuted only byone 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-C These are looking as keywords but infact these are methods of root class

    NSObject.

    alloc retain release autorelease

    Some other keywords:1. bool is a keyword used in objective-C but its value is here YES or NO.In C and C++ it has value either TRUE or FALSE. 2. 'super' and 'self' can be treated as keywords but self is a hiddenparameter to each method and super gives the instructions to thecompiler that how to use self differently.

    Preprocessor Directives The preprocessor directives are special notations:

    Directive Definition

    // This is used to comment asingle line.

  • 8/3/2019 OOPS Objectivec1

    15/15

    Copyright 2009 EDUmobile.org All Rights Reserved

    M O B I L E T R A I N I N GEDUmobile.org

    #import Like C and C++ it is used toinclude a file but it doesn'tinclude more than once.