ios chapter 1 basic

Upload: seethalakshmi-sethurajan

Post on 14-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 Ios Chapter 1 Basic

    1/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    Basic concepts of Objective C

    Before writing programs for iPhone one need to know which programming language is used to write programs

    for iPhone.

    For writing programs for iPhone we use Objective C language and COCOA framework.

    Thus as new iPhone developer we will require to get fare knowledge about the Objective C language.

    The Objective-C language is a simple computer language designed to enable object-oriented programming.

    Objective-C is defined as a small but powerful set of extensions to the standard ANSI C language. The additions

    are mostly based on Smalltalk, one of the first Object-Oriented programming languages. Objective-C is designed

    to give C full Object-Oriented programming capabilities.

    Lets look into the various concepts of Objective C

    Objects

    Every Object-Oriented Programming language is build around Objects. So one can say Objects are buildingblocks of Object-Oriented Programming language.

    Objects are key to understanding object-oriented technology. Look around right now and you'll find many

    examples of real-world objects: your phone, your desk, your television set and so on.

    Real-world objects share two characteristics: They all havestate and behavior. Phone has state (name, color, ring

    tone) and behavior (ringing, ideal, waiting). Identifying the state and behavior for real-world objects is a great

    way to begin thinking in terms ofobject-orientedprogramming.

    Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An

    object stores its state in fields (variables in some programming languages. In case of Objective C its properties)

    and exposes its behavior through methods (functions in some programming languages). Methods operate on an

    object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal

    state and requiring all interaction to be performed through an object's methods is known as data encapsulation

    a fundamental principle of object-oriented programming.

    Making code into individual software objects provides a number of benefits, including:

    Modularity

  • 7/30/2019 Ios Chapter 1 Basic

    2/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    The source code for an object can be written and maintained independently of the source code for other objects.

    Once created, an object can be easily passed around inside the system.

    Information-hiding

    By interacting only with an object's methods, the details of its internal implementation remain hidden from the

    outside world.

    Code re-use

    If an object already exists (perhaps written by another software developer), you can use that object in your

    program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then

    trust, to run in your own code.

    4.Plug ability and debugging ease:

    If a particular object turns out to be problematic, you can simply remove it from your application and plug in a

    different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt

    breaks, you replace it, not the entire machine.

    Thus various properties and methods, which manipulate these properties, are encapsulated to form an Object.

    An Object sees only those methods that were designed for it.

    In Objective C object identifiers identifies object, which is distinct data type. This identifier is called as id.

    This type is defined as a pointer to an objectin reality, a pointer to the instance variables of the object, the

    objects unique data. Like a C function or an array, an object is identified by its address.

    All objects, regardless of their instance variables or methods, are of type id.

    Objective Cconstructor returns id.

    NOTE: The keyword nil is defined as a null object, an id with a value of 0. id, nil, and the other basic types of

    Objective-C are defined in the header file objc/objc.h.

    An object doesn't exist until an instance of the class has been created; the class is just a definition. When the

    object is physically created, space for that object is allocated RAM. It is possible to have multiple objects created

    from one class.

    id and isa

    id by itself yield no information about the object expect it is an object.

  • 7/30/2019 Ios Chapter 1 Basic

    3/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    All objects are not same. For example, a Rectangle object will not have all same properties & methods or

    instance variables as that of object that represent a bit mapped image.As a programmer, we know that at some point of time complier or program itself needs to find more specific

    information about an object i.e. what objects instance variables are, what method it can perform etc.

    id doesnt supply this information to complier but object has to be able to supply such information during runtime

    so that application can run appropriately. This is possible because object carries with it an isa instance variable

    that identifies the objects class i.e. what kind of object is and so on.

    Thus for example, every Rectangle object would be able to tell the runtime system that it is Rectangle, similarly

    every Circle can say that it is Circle.

    Thus we can conclude objects with the same behavior (methods) & same kind of data (instance variable) are

    member of same class.

    So system can know at the about an object thus objects are dynamically typed at runtime.

    So, the runtime system can find the exact class that an object belongs, just by asking the object.

    Note:

    Dynamic Typing is the basic building block of dynamic binding in Objective C language.

    Also isa pointer of an object enables object to perform introspection, a mechanism to find out about themselves

    (or other objects).

    Now lets start how things work in this system

    1. The complier records information about the class definitions in the data structure for the runtime system

    to use.

    2. The functions of the run time system uses isa to find this information at runtime.

    3. Using this information runtime system gather various information such what methods object can perform,

    name of its superior class and so on.

    4. As in real world we communicate with other objects through messages which can be verbal or non verbal.

    5. Similarly objects in Objective C communicate with other objects through messages. Basically in programming

    to enable communication between various parts of the program we use function call. Thus messages are nothing

    but simple function call.

    Object Messaging

    Consider following programming structure for better

  • 7/30/2019 Ios Chapter 1 Basic

    4/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    There are two classes A and B, we will see how object from class A communicate with object of class B in

    order to perform some task which object of class B can perform.

    Class A

    {

    int nVariableA;

    B *b;

    nVariableA = b.someFunction(); 1. Object of Class A sendmessage to Class B object.

    }

    Class B

    {

    int someFunction() 2. Class B object receives message from class A object.

    {

    .

    . 3. Class B object perform respective task.

    .return (value); 4. Class B object sends the feedback to Class A object.

    }

    }

    In objective C we write function call i.e. sending message syntax as follows

    [Receiver message]; is equivalent to Receiver.message();

    Thus in above example nVariable = b.someFunction(); is represented as

    nVariable = [b someFunction];

    Thus Receiver = the object whose function one has to use

    message = method or function which one has to use

    Lets consider few more example to get clear picture of message syntax in Objective C

    [myRect display];

    This above statement calls display method of myRect (object) which say belongs to Rectangle class.

  • 7/30/2019 Ios Chapter 1 Basic

    5/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    [myRect setOrigin:30.0 :50.0];

    Here message setOrigin has two arguments. This message tells myRect to set its origin to window co ordinates

    30.0 and 50.0 respectively.

    One has notice there two colons each for arguments. Arguments are inserted after the colon.

    In the above message, the method uses unlabeled arguments. Unlabeled arguments make it difficult to determine

    the kind & purpose of the methods arguments. Thus method name should include labels describing each of

    respective argument.

    Argument label precedes each colon in the method name.

    [myRect setDimensionWidth:10.0 Height:15.0];

    The above message call clearly indicates that myRect object will set the dimension, which are nothing but width

    and height.

    Methods can take a variable number of arguments though they are use rarely. Extra arguments are separated by

    comma.

    [receiver myGroup:group,memberOne,memberTwo];

    Here myGroup method is passed with one required argument (group) and are two optional arguments which are

    memberOne and memberTwo.

    In order to complete the communication cycle we require a feedback from the receiver, which is nothing but a

    return type. Thus every message need to provide the return type.

    nVariable = [b someFunction];

    Here someFunction has return type as int.

    We can have nested message as follows

    [myRect setPrimaryColor:[otherRect primaryColor]];

    Here the color of one Rectangle is set to the color of another Rectangle.

  • 7/30/2019 Ios Chapter 1 Basic

    6/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    With this example we uncover one more interesting concept regarding Receivers instance variable.

    As we can see primaryColor method takes no argument yet it can find the primary color for otherRect and return.

    Thus method has automatic access to the receivers instance variable. Thus we dont have to pass them as

    methods argument.

    This situation is like when we receive mail; it contains information about something outside our home.

    Information about our home is already with us and we can access it & thus it is not there in the mail.

    If object requires information about a variable stored in another object, it must send a message to the object

    asking it to reveal the content of the variable, which is also shown in above example.

    Polymorphism

    In particular, an object can be operated on by only those methods that were defined for it. It cant confuse them

    with methods defined for other kinds of objects, even if another object has a method with the same name.

    This means that two objects can respond differently to the same message. For example, each kind of object sent a

    display message could display itself in a unique way. A Circle and a Rectangle would respond differently to the

    display message.

    This feature, referred to as polymorphism.

    Together with dynamic binding, it permits you to write code that might apply to any number of different kinds of

    objects, without you having to choose at the time you write the code what kinds of objects they might be. They

    might even be objects that will be developed later, by other programmers working on other projects. If you write

    code that sends a display message to an id variable, any object that has a display method is a potential receiver.

    Dynamic Binding

    A crucial difference between function calls and messages is that a function and its arguments are joined together

    in the compiled code, but a message and a receiving object arent united until the program is running and the

    message is sent.

    Therefore, the exact method thats invoked to respond to a message can only be determined at runtime, not when

    the code is compiled.

    The precise method that a message invokes depends on the receiver. Different receivers may have different

    method implementations for the same method name (polymorphism).

  • 7/30/2019 Ios Chapter 1 Basic

    7/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    For the compiler to find the right method implementation for a message, it would have to know what kind of

    object the receiver iswhat class it belongs to. This is information the receiver is able to reveal at runtime. Thusterm Dynamic Binding.

    Note: How it works?

    The selection of a method implementation happens at runtime.

    When a message is sent, a runtime messaging routine looks at the receiver and at the method named in the

    message.

    It locates the receivers implementation of a method matching the name, calls the method, and passes it apointer to the receivers instance variables.

    This dynamic binding of methods to messages & polymorphism gives object-oriented programming much of its

    flexibility and power. Since each object can have its own version of a method, a program can achieve a variety of

    results, not by varying the message itself, but by varying just the object that receives the message.

    This can be done as the program runs; receivers can be decided on the fly and can be made dependent on

    external factors such as user actions.

    Inheritance

    As we know what inheritance means, anyways we give one line definition it is process of generalization to

    specialization.

    Like in java we have Object as root class for every class written in java. Similarly we have NSObject is a base

    class. This class defines basic framework for Objective C objects & object interaction.

    It impart to the classes & instances of class that inherits from it the ability to behave as objects & cooperate with

    the runtime system.

    Note:

    Implementing a new root class is a delicate task & one with many hidden hazards. The class must duplicate much

    of what the NSObject class does, such as allocate instances, connect them to their class & identify them to the

    runtime system. So one should generally use the NSObject class provided with COCOA as the root class. The

    sample class structure is as shown below

  • 7/30/2019 Ios Chapter 1 Basic

    8/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    Coding representation of above figure is shown below

    One can override the super class method known as function overriding.

    Note:

    The complier creates just one accessible object for each class, a user object that knows how to build new objects

    belonging to the class are know as factory object.

    The class object is the complete version of the class; the objects it builds are instance of the class.

    The objects that do the main work of your program are instance created by the class object at runtime.

    Convention, class name begins with Uppercase while name of instance begins with lower case.

    One can use class name in place of id to designate an objects type.

    Rectangle *myRect;

    This way declaring an object type, which gives the complier information about the kind of object, is known as

    static typing.

    Just as id is defined as a pointer to an object, objects are statically typed as pointer to a class. Static typing makes

    the pointer explicit; id hides it.

    As Rectangle is a kind of Graphic , a Rectangle instance could be statically typed to the Graphic class as

    Graphic *myRect;

    This is possible because Rectangle is a Graphic. Its more than a Graphic since it also has the instance variable &

    method capabilities of a shape & Rectangle; but its a Graphic nevertheless.

    For purpose of type checking, the complier consider myRect to be Graphic, but at runtime its treated as a

    Rectangle.

    Class Object

    The complier creates just one accessible object for each class, a class object is one who knows to build new

    objects belonging to the same class, also know as factory object.

  • 7/30/2019 Ios Chapter 1 Basic

    9/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    A class definition contains following information, much of it about instances of the class:

    1. The name of the class and its super class.2. A template describing a set of instance variables.

    3. The declarations of method names and their return and argument types.

    4. The method implementations

    The class object has access to all the information about the class, which means mainly information about what

    instances of the class are like.

    Although a class object keeps the prototype of a class instance, its not an instance itself.

    A class definition can include methods intended specifically for the class object, class methods as opposed to

    instance methods.

    A class object inherits class methods from the classes above it in the hierarchy, just as instances inherit instance

    methods.

    Class objects are thus full-fledged objects that can be dynamically typed, receive messages, and inherit methods

    from other classes.

    Theyre special only in that the compiler creates them; lack data structures (instance variables) of their own other

    than those built from the class definition, and are the agents for producing instances at runtime.

    Consider the following example,

    int value = [Rectangle version];

    You would have notice the Class Name appears in the receiver position of the message, which is nothing but

    class object. This statement calls class method version which is declared inside the Rectangle class.

    Creating Instances

    A principal function of a class object is to create new instances.

    Consider following code line

    id myRect;

    myRect = [Rectangle alloc];

    The alloc method dynamically allocates memory for the new objects instance variables and initializes them all to

    0all, that is, except the isa variable that connects the new instance to its class.

  • 7/30/2019 Ios Chapter 1 Basic

    10/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    For an object to be useful, it generally needs to be more completely initialized. Thats the function of an init

    method. Initialization typically follows immediately after allocation:

    myRect = [[Rectangle alloc] init];

    Thus after initialization the instance objects are ready to receive messages.

    The alloc method returns a new instance and that instance performs an init method to set its initial state. Every

    class object has at least one method (like alloc) that enables it to produce new objects, and every instance has at

    least one method (like init) that prepares it for use.

    Thus above line of code tells complier that create and allocate memory for a Rectangle object and also initialize it

    to ready state, and assign to variable myRect.

    1.9 Classes

    In Objective C classes are defined in two parts

    1. An interface that declares the methods and instance variables of the class and names its super class.

    2. An implementation that actually defines the class (contains the code that implements its methods).

    Interface and implementation files typically are named after the class.

    The name of the implementation file has the .m extension, indicating that it contains Objective-C source code.

    The name of the interface file usually has the .h extension typical of header files.

    For example, the Rectangle class would be declared in Rectangle.h and defined in Rectangle.m.

    Separating an objects interface from its implementation fits well with the design of object-oriented programs. An

    object is a self-contained entity that can be viewed from the outside almost as a black box. Once youve

    determined how an object interacts with other elements in your programthat is, once youve declared itsinterfaceyou can freely alter its implementation without affecting any other part of the application.

    The declaration of a class interface begins with the compiler directive @interface and ends with the directive

    @endas shown below.

    @interface ClassName : ItsSuperclass

    {

    instance variable declarations

  • 7/30/2019 Ios Chapter 1 Basic

    11/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    }

    method declarations

    @end

    Note:

    If the colon and super class name are omitted, the new class is declared as a root class, a rival to the NSObject

    class.

    Now lets consider Rectangle class interface

    @interface Rectangle : Shape

    {

    float width;float height;

    BOOL filled;

    float radius;

    :

    :

    :

    NSColor *fillColor;

    }

    + alloc;

    + Sign indicates it is Class object method i.e. Class Method.

    - (void) display;

    - Sign indicates it is instance variable method i.e. instance method.

    - (float) radius;

    Return type of message. By default it is an id.

    - (void) setRadius: (float) aRadius;

  • 7/30/2019 Ios Chapter 1 Basic

    12/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    -- Type of argument passed inside the method.

    - (void) setWidth: (float) width Height: (float) height;

    If there is more than one argument, the arguments are declared within the method name after colon.

    Note:

    One can define class method & instance method with same name.

    A method can also have same name as an instance name variable. This is more common especially if the

    method returns a value in the variable. For example, Circle has a radius method that could match a radius

    instance variable.

    The interface is usually included with the #import directive.

    This directive is identical to #include, except that it makes sure that the same file is never included more than

    once.

    # import Rectangle.h

    An interface file begins by importing the interface for its super class.

    This convention means that every interface file includes, indirectly, the interface files for all inherited classes.When a source module imports a class interface, it gets interfaces for the entire inheritance hierarchy that the

    class is built upon.

    #import "ItsSuperclass.h"

    @interface ClassName : ItsSuperclass

    {

    instance variable declarations

    }

    method declarations

    @end

    An interface file declares a class and, by importing its super class, implicitly contains declarations for all

    inherited classes, from NSObject on down through its super class.

    If the interface mentions classes not in this hierarchy, it must import them explicitly or declare them with the

    @class directive.

  • 7/30/2019 Ios Chapter 1 Basic

    13/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    For example,

    @class Rectangle, Circle;

    This directive simply informs the compiler that Rectangle and Circle are class names. It doesnt import their

    interface files.

    Now consider following code written in interface line

    -(void)setPrimaryColor:(NSColor *)aColor;

    Such declarations simply use the class name as a type and dont depend on any details of the class interface (its

    methods and instance variables).

    Thus an interface file uses @class to declare classes, and the corresponding implementation file imports their

    interfaces since it will need to create instances of those classes or send them messages.

    The definition or implementation of class begins with @ implementation directives & ends with the @end

    directive.

    #import ClassName.h

    @implementation ClassName

    All Methods implementation

    @end

    Note:

    Every implementation file must import its own interface. This is because the implementation doesnt need to

    repeat any of the declarations it imports, it can safely omit.

    Specifiers are denoted by @private, @public & @protected directives. By default it is protected.

    Consider the following code

    @interface Worker : NSObject

  • 7/30/2019 Ios Chapter 1 Basic

    14/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    {

    char *a ; by default it is protected.

    @private

    int nAge;

    char *charEvaluation;

    @protected

    id job;

    float fltWage;

    @public

    id boss;}

    @end

    Instance variables that a class declares, no matter how they are marked are within the scope of the class

    definitions

    For example, consider some function definition of Worker class

    - (Position*) promote: (Position*) newPosition

    {

    id old = job;

    job = newPosi tion; This function refers job instance as it knowsIn short method of class can uses

    Instances of that class disrespect to their

    access specifiers.

    return old;

    }

    Default return type is id.

    Following figure gives you clear picture of access specifiers

    1. 10 Categories & Extentions

    Now we know how to declare and define a class lets extend our knowledge on how to add more functionality on

  • 7/30/2019 Ios Chapter 1 Basic

    15/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    existing class.

    There are two different ways

    1.10.1 Categories

    A category allows programmer to add methods to an existing classeven to one to which programmer do not

    have the source.

    This powerful feature allows programmer to extend the functionality of existing classes without sub classing.

    One can add methods to a class by declaring them in an interface file under a category name and defining them in

    an implementation file under the same name.

    The category name indicates that the methods are additions to a class declared elsewhere, not a new class.

    The interface and implementation block of the category is as shown below

    #import "ClassName.h" Need to import ClassName so that we can get access to allvariable & methods of ClassName which can be use to add more

    functions.

    @interface ClassName ( CategoryName )

    // method declarations

    @end

    #import "ClassName+CategoryName.h"

    @implementation ClassName ( CategoryName )

    // method definitions

    @end

    Due to naming convention we save category interface by using ClassName+CategoryName.h and implementation

    file ClassName+CategoryName.m respectively.

    We cannot add instance variable through category but we can access all the variables of class even private

    variables.

    There is no limit to the number of categories that you can add to a class, but each category name must be

    different, and each should declare and define a different set of methods.

  • 7/30/2019 Ios Chapter 1 Basic

    16/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    Category can override method declared in class interface but not of another category, as category is not a

    substitute of subclass.

    1.10.2 Extensions

    Class extensions are like anonymous categories, except that the methods they declare must be

    implemented in the main @implementation block for the co rresponding class.

    For example, the compiler will compile without error the following declarations and implementation:

    =============================================================

    @interface MyObject : NSObject

    {

    NSNumber *number;

    }

    -(NSNumber *)number;

    @end

    @interface MyObject (Setter)

    -(void)setNumber:(NSNumber *)newNumber;

    @end

    =============================================================

    @implementation MyObject

    -(NSNumber *)number

    {

    return number; @end

    }

    Note that there is no implementation of the setNumber method. If it is invoked at runtime, this will generate anerror.

    Class extensions allow you to declare additional required API for a class in locations other than within the

    primary class @interface block, as illustrated in the following example:

    =============================================================

    MyObject.h

    @interface MyObject : NSObject

    {

    NSNumber *number;

  • 7/30/2019 Ios Chapter 1 Basic

    17/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    }

    -(NSNumber *)number;

    @end

    @interface MyObject ()

    -(void)setNumber:(NSNumber *)newNumber;

    @end

    =============================================================

    =============================================================

    MyObject.m

    @implementation MyObject-(NSNumber *)number

    {

    return number;

    }

    -(void)setNumber(NSNumber *)newNumber

    {

    number = newNumber; @end

    }

    No name is given in the parentheses in the second @interface block.

    The implementation of the setNumber method appears within the main @implementation block for the class.

    The implementation of the setNumber method must appear within the main @implementation block for the class

    (you cannot implement it in a category). If this is not the case, the compiler will emit a warning that it cannot find

    a method definition for setNumber.

    1. 11 Properties

    @ interface Rectangle : NSObject

    {

    int a;

    int width;

    }

  • 7/30/2019 Ios Chapter 1 Basic

    18/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    @property () int a;

    @end

    @ implementation Circle

    -(void) someFunction

    {

    Rectangle *rect = [[Rectangle alloc] init];

    Int b = 1000;

    Rect.a = 1000;

    }

    This feature provides a simple way to implement an objects properties declaratively. It also provides a concise

    syntax for accessing properties of objects without the need to write accessor methods.

    In short we know that one have to provide getter & setter methods for each instance i.e. property of the class

    through which one can assign value & retrieve value for the particular instance variable of the class.

    The Objective-C declared properties feature offers the following advantages

    The property declaration provides a clear, explicit specification of how the accessor method behaves.Thus according to the specification one provide, complier can synthesize accessor methods for the developer,

    thus reduce the programmers work for writing accessor methods code & over all size of program.

    As properties are syntactically represented as identifiers & are scoped, so the complier can detect use of

    undeclared properties.

    Runtime introspection of the properties declared by a class.

    As OOP rule states anything, which need to be used, requires to be declared. As properties are represented as an

    identifier thus before using them in implementation block, they are required to be declared in method declaration

    or categories or extensions block of interface block.

  • 7/30/2019 Ios Chapter 1 Basic

    19/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    For declaring a property we use compiler directive @property in the method declaration section of an interface

    block.

    The general syntax of property is as shown below

    @property (attributes) type name;

    @property = It complier declarative to indicate property is been declared.

    attributes = Attributes are enclosed in round parenthesis, multiple attributes

    separated by comma within parenthesis.

    type = data type of property.

    name = name of instance of the class on which property is assigned.

    Consider following example for declaring the property

    @interface MyClass : NSObject

    {

    NSString *value;

    }

    @property(copy, readwrite) NSString *value;

    @end

    Once we declare property in an interface block we need to implement that property in an implementation block of

    the code.

    There are two ways through which one can implement the property in the implementation block.

    By using complier directive @synthesize

    With this method of implementation one tells complier to synthesize the setter and/or getter methods for the

    property & programmer will not write code for setter & getters methods for the property in the @implementation

    block.

    Thus implementation of property name using synthesize will be as follows

    @implementation MyClass

  • 7/30/2019 Ios Chapter 1 Basic

    20/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    @synthesize value; property name which is implemented.

    @end

    With such implementation programmer code will not contain getter & setter methods for the value.

    One can use following form also while implementing property

    property = ivar;

    This tells complier that a particular instance variable (ivar) should be used for the property.

    Consider following line of code

    @synthesize firstName, lastName, age = yearsOld;

    This specifies that the accessor methods for firstName, lastName, and age should be synthesized and that the

    property age is represented by the instance variable yearsOld.

    By using complier directive @dynamic

    With this implementation one tell the compiler that programmer will provide accessor methods for the property either byproviding method implementations directly or at runtime using other mechanisms such as dynamic loading of code or

    dynamic method resolution.

    In short programmer will provide the getter and setter methods for the property i.e. the

    implementation block.

    @interface MyClass : NSObject

    {

    NSString *value;

    }@property(copy,readwrite) NSString *value;

    @end

    @implementation MyClass

    @dynamic value;

    - (NSString *)value

  • 7/30/2019 Ios Chapter 1 Basic

    21/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    {

    return value;

    }

    -(void)setValue:(NSString *)newValue

    {

    if (newValue != value)

    {

    value = [newValue copy]; or value = newValue;

    }

    }

    @end

    By default implementation of the property is @dynamic i.e. if developer dont specify either @synthesize or

    @dynamic for a particular property than developer must provide getter & setter method implementation for that

    property.

    As convention name of the instance variable is used as getter method.

    [myRect origin];

    myRect = Object of the Rectangle class

    origin = this is variable name, but in message it call getter method which return

    value of origin.

    For setter name is setOrigin i.e. set followed by property name.

    The getter must return a type matching the property type & take no arguments.

    The setter method must take single argument of a type matching the propertys type & must return void.

    The default names are names propertyName & setPropertyName for getter & setter respectively. For example,

    given a property foo its accessor will be foo & setFoo.

    Now we know how to declare and implement the property, but question comes how to access the property.

    For accessing property one have to use dot operator, syntax for same is as shown below

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

    myInstance.value = @New Value;

    NSLog(@Value is : %@ ,myInstance.value);

  • 7/30/2019 Ios Chapter 1 Basic

    22/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    If one does not use dot operator for accessing property than above code needs to be written as follows

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

    [myInstance setValue:@New Value];

    NSLog(@Value is : %@ ,[myInstance value]);

    While declaring the property we use attributes for the property. Attributes gives property an additional flavor i.e.

    additional meaning to the property in order to tell how property should behave accordingly to the environment.

    Following are the lists of attributes which are used with property

    readonly

    Indicates that the property is read-only.

    The default is readwrite.

    If you specify readonly, only a getter method is required in the @implementation, or if you use @synthesize only

    the getter method is synthesized.

    Moreover, if you attempt to assign a value using the dot syntax, you get a compiler error.

    readwrite

    Indicates that the property should be treated as read/write.

    This is the default.

    Both a getter and setter method will be required in the @implementation, or if you use @synthesize the getter and

    setter methods are synthesized.

    assign

    Specifies that the setter uses simple assignment.

    This is the default.

    Note: If your application uses garbage collection, if you want to use assign for a property whose class adopts the

    NSCopying protocol you should specify the attribute explicitly rather than simply relying on the default

    otherwise you will get a compiler warning. (This is to reassure the compiler that you really do want to assign the

    value, even though its copyable.)

    The assign is basically use to assign value to the property.

    retain

  • 7/30/2019 Ios Chapter 1 Basic

    23/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    Specifies that retain should be invoked on the object upon assignment. (The default is assign.)

    Note: This attribute is valid only for Objective-C object types.

    By using retain we guarantee that object will retain in memory when property is assigned with value.

    The setter method of property with retain attribute will be as follows

    if (property != newValue)

    {

    [property release];

    property = [newValue retain];}

    copy

    Specifies that a copy of the object should be used for assignment. (The default is assign.) Invoking the copy

    method makes the copy. This attribute is valid only for object types,

    which must implement the NSCopying protocol.

    This is often useful for attributes such as NSStrings objects where there is a possibility that the new values passed

    in a setter may be mutable & you want to ensure that your object has its own private immutable copy.

    For example,

    @property (copy) NSString *string;

    -(void) setString: (NSString *) newString

    {

    if (string != newString)

    {

    [string release];

    string = [newString copy]; This normally return a final value whichcannot be change.

    }

    }

    Although this works fine well with string but creates problem while working with collection such as array or set.

    As collection are often mutable but copy method returns immutable version of the collection. In other words copy

    makes object immutable.

    In such situation one should provide their own implementation of the setter method

  • 7/30/2019 Ios Chapter 1 Basic

    24/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    @interface MyClass: NSObject

    {

    NSMutableArray *myarray;}

    @property (copy) NSMutableArray *myarray;

    @end

    @implementation MyClass

    @dynamic myarray;

    -(void) setMyarray: (NSArray *)newArray

    {

    if(myarray != newArray)

    {

    [myarray release];

    myarray = [newArray mutuablecopy];

    }

    }

    @end

    nonatomic

    Specifies that accessors are non-atomic. By default, accessors are atomic.

    This is so that default synthesized accessor provide robust access to properties in a multi-threaded environment

    that is, the value returned from the getter or set via the setter is always fully retrieved or set regardless of what

    other threads are executing simultaneously.

    If you do not specify nonatomic, then in a managed memory environment a synthesized get accessor for an object

    property retains and autoreleases the returned value; if you specify nonatomic, then a synthesized accessor for an

    object property simply returns the value directly.

    Note:

    You can re-declare a property in a subclass, but (with the exception of readonly vs. readwrite) you must repeat its

    attributes in whole in the subclasses. The same holds true for a property declared in a category or protocol

    while the property may be re declared in a category or protocol, the propertys attributes must be repeated in

    whole.

  • 7/30/2019 Ios Chapter 1 Basic

    25/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    // public header file

    @interface MyObject : NSObject

    {NSString *language;

    }

    @property (readonly, copy) NSString *language;

    @end

    // private implementation file

    @interface MyObject ()

    @property (readwrite, copy) NSString *language;

    @end

    @implementation MyObject

    @synthesize language;

    @end

    1.11 Protocol

    Protocols declare methods that can be implemented by any class. Protocols are useful in at least three situations:

    To declare methods that others are expected to implement.

    To declare the interface to an object while concealing its class.

    To capture similarities among classes those are not hierarchically related.

    Class and category interfaces declare methods that are associated with a particular classmainly methods that

    the class implements. Protocols, on the other hand, declare methods not associated with a class, but which any

    class, and perhaps many classes, might implement.

    A protocol is simply a list of method declarations, unattached to a class definition. For example, these methods

    that report user actions on the mouse could be gathered into a protocol:

    - (void)mouseDown:(NSEvent *)theEvent;

    -(void)mouseDragged:(NSEvent *)theEvent;

    -(void)mouseUp:(NSEvent *)theEvent;

    Any class that wanted to respond to mouse events could adopt the protocol and implement its methods.

    Protocols define method declarations independent of the class hierarchy, so they can be used in ways that classes

    and categories cannot.

  • 7/30/2019 Ios Chapter 1 Basic

    26/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010. Tel.:- +91 986 935 7889 Email:- [email protected] Web:- www.nimapinfotech.com

    Protocols list methods that are (or may be) implemented somewhere, but the identity of the class that implements

    them is not of interest.

    What is of interest is whether or not a particular class conforms to the protocolwhether it has implementations

    of the methods the protocol declares.

    Thus objects can be grouped into types not just on the basis of similarities due to the fact that they inherit from

    the same class, but also on the basis of their similarity in conforming to the same protocol.

    Classes in unrelated branches of the inheritance hierarchy might be typed alike because they conform to the same

    protocol.

    You declare protocols with the @protocol directive.

    @protocol ProtocolName

    method declarations

    @end

    Protocol methods can be marked as optional using the @optional keyword.

    Corresponding to the @optional modal keyword, there is a @required keyword to formally denote the semanticsof the default behavior.

    You can use @optional and @required to partition your protocol into sections as you see fit.

    If you do not specify any keyword, the default is @required.

    @protocol MyProtocol

    -(void)requiredMethod;

    @optional

    -(void)anOptionalMethod;

    -(void)anotherOptionalMethod;

    @required

    -(void)anotherRequiredMethod;

    @end

    Just as classes are represented at runtime by class objects and methods by selector codes, a special data type

  • 7/30/2019 Ios Chapter 1 Basic

    27/27

    Nimap Infotech, B-204, Pawapuri Apts, Love Lane, Mumbai 400010.

    instances of the Protocol class, represents protocols.

    Adopting a protocol is similar in some ways to declaring a super class.

    Both assign methods to the class. The super class declaration assigns it inherited methods; the protocol assigns it

    methods declared in the protocol list.

    A class is said to adopt a protocol if in its declaration it lists the protocol within angle brackets after the super

    class name.

    @interface ClassName : ItsSuperclass < protocol list >

    Categories adopt protocols in much the same way:

    @interface ClassName ( CategoryName ) < protocol list >

    A class can adopt more than one protocol; names in the protocol list are separated by commas.

    @interface Formatter : NSObject < Formatting, Prettifying >

    Since a class must implement all the required methods declared in the protocols it adopts, saying that a class or an

    instance conforms to a protocol is equivalent to saying that it has in its implements all the methods the protocoldeclares.