Thursday, September 8, 2011

Reverse Mapping

I have Implemented one more thing and that is Reverse Mapping for iPhone and iPad.Now We can take all information using map like if i click on the map it will returns the latitude and Longitude of that particular Place and using Forward Geocoding we can get the Address of that Particular location.

With iOS 3.2 or greater, it's probably better and simpler to use a UIGestureRecognizer with the map view instead of trying to subclass it and intercepting touches manually.First, add the gesture recognizer to the map view:

UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc]
initWithTarget
:self action:@selector(tapGestureHandler:)];
tgr
.delegate = self; //also add to @interface
[mapView addGestureRecognizer:tgr];
[tgr release];

Next, implement shouldRecognizeSimultaneouslyWithGestureRecognizer and return YES so your tap gesture recognizer can work at the same time as the map's
(otherwise taps on pins won't get handled automatically by the map):


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer
:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}


Finally, implement the gesture handler:

- (void)tapGestureHandler:(UITapGestureRecognizer *)tgr
{
CGPoint touchPoint = [tgr locationInView:mapView];

CLLocationCoordinate2D touchMapCoordinate
= [mapView convertPoint:touchPoint toCoordinateFromView:mapView];

NSLog(@"tapGestureHandler: touchMapCoordinate = %f,%f",
touchMapCoordinate
.latitude, touchMapCoordinate.longitude);
}

Saturday, June 12, 2010

Essential Development Tasks


The iPhone-application development process is divided into these major steps:

  1. Create your project.

    Xcode provides several project templates that get you started. You choose the template that implements the type of application you want to develop. See “Creating an iPhone Project” for details.

  2. Design the user interface.

    The Interface Builder application lets you design your application’s user interface graphically and save those designs as resource files that you load into your application at runtime. If you do not want to use Interface Builder, you can layout your user interface programmatically. See “User Interface Design Considerations” in iPhone Application Programming Guide for more information.

  3. Write code.

    Xcode provides several features that help you write code fast, including class and data modeling, code completion, direct access to documentation, and refactoring. See “Editing Code” for details.

  4. Build and run your application.

    You build your application on your computer and run it in the iPhone Simulator application or on your device. See “Building and Running Your Application” for more information.

  5. Measure and tune application performance.

    After you have a running application, you should measure its performance to ensure that it uses a device’s resources as efficiently as possible and that it provides adequate responses to the user’s gestures. See “Measuring Application Performance” for more information.

The rest of this section gives more details about these steps.

Creating an iPhone Project

The iPhone SDK provides several project templates to get you up and running developing your application. You can choose from these types of application:

  • Navigation-Based Application. An application that presents data hierarchically, using multiple screens. The Contacts application is an example of a navigation-based application.

  • OpenGL ES Application. An application that uses an OpenGL ES–based view to present images or animation.

  • Tab Bar Application. An application that presents a radio interface that lets the user choose from several screens. The Clock application is an example of a tab bar application.

  • Utility Application. An application that implements a main view and lets the user access a flip-side view to perform simple customizations. The Stocks application is an example of a utility application.

  • View-Based Application. An application that uses a single view to implement its user interface.

  • Window-Based Application. This template serves as a starting point for any application, containing an application delegate and a window. Use this template when you want to implement your own view hierarchy.

If you need to develop a static library for use in an iPhone application, you can add a static library target to your project by choosing Project > New Target and selecting the Static Library target template in the iPhone OS/Cocoa Touch list.

Static libraries used in iPhone applications do not need to be code signed. Therefore, you should remove the Code Signing Identity build setting definition from the static library targets you create. To do so:

  1. Open the static-library target’s Info window and display the Build pane.

  2. In the Code Signing group, select the Any iPhone OS Device conditional definition for the Code Signing Identity build setting.

  3. Change the conditional definition’s value from iPhone Developer to Don’t Code Sign.

To learn more about the iPhone application architecture, see iPhone Application Programming Guide.

To develop an iPhone application, you work on an Xcode project. And you do most of your work on projects through the project window, which displays and organizes your source files and other resources needed to build your application. This window allows you to access and edit all the pieces of your project. Figure 1-1 shows the project window.

Figure 1-1 Project window

The project window identifying the toolbar, favorites bar, Groups  & Files list, status bar, and detail view.

The project window contains the following key areas for navigating your project:

  • Groups & Files list. Provides an outline view of your project’ contents. You can move files and folders around and organize your project contents in this list. The current selection in the Groups & Files list controls the contents displayed in the detail view.

  • Detail view. Shows the item or items selected in the Groups & Files list. You can browse your project’s contents in the detail view, search them using the search field, or sort them according to column. The detail view helps you rapidly find and access your project’s contents.

  • Toolbar. Provides quick access to the most common Xcode commands.

  • Favorites bar. Lets you store and quickly return to commonly accessed locations in your project. The favorites bar is not displayed by default. To display the favorites bar, choose View > Layout > Show Favorites Bar.

  • Status bar. Displays status messages for the project. During an operation—such as building or indexing—Xcode displays a progress indicator in the status bar to show the progress of the current task.

To learn more about creating projects, see “Creating Projects”.

Editing Code

The main tool you use to write your code is the Xcode text editor. This advanced text editor provides several convenient features:

  • Header-file lookup. By Command–double-clicking a symbol, you can view the header file that declares the symbol.

  • API reference lookup. By Option–double-clicking a symbol, you get access to API reference that provides information about the symbol’s usage.

  • Code completion. As you type code, you can have the editor help out by inserting text for you that completes the name of the symbol Xcode thinks you’re going to enter. Xcode does this in an unobtrusive and overridable manner.

  • Code folding. With code folding, you can collapse code that you’re not working on and display only the code that requires your attention.

For details about these and other text editor features, see “The Text Editor”.

Using Code Completion

The text editor helps you type code faster with code completion. When code completion is active, Xcode uses both text you have typed and the context into which you have typed it to provide suggestions for completing the token it thinks you intend to type. Code completion is not active by default.

To activate code completion:

  1. Open the Xcode Preferences window.

    Choose Xcode > Preferences.

  2. In the Code Completion section of the Code Sense pane, choose Immediate from the Automatically Suggest pop-up menu.

  3. Click OK.

As you type the name of a symbol, Xcode recognizes that symbol and offers a suggestion, as shown in Figure 1-2. You can accept suggestions by pressing Tab or Return. You may also display a list of completions by pressing Escape.

Figure 1-2 Using code completion

Example of code completion in action. Text entered “CGPointM”,  completion shown: “ake(CGFloat x, CGFloat y).

To learn more about code completion, see “Completing Code” in Xcode Workspace Guide.

Accessing Documentation

During development, you may need fast access to reference for a particular symbol or high-level documentation about API usage or an iPhone OS technology. Xcode gives you easy access to such resources through the Research Assistant and the Documentation window.

The Research Assistant is a lightweight window, shown in Figure 1-4, that provides a condensed view of the API reference for the selected item, without taking your focus away from the editor in which the item is located. This window provides an unobtrusive way to consult API reference. However, when you need to dig deeper into the reference, the Documentation window is just a click away.

The Documentation window (Figure 1-3) lets you browse and search the developer documentation (which includes API reference, guides, and articles about particular tools or technologies) installed on your computer. It provides access to a wider and more detailed view of the documentation than the Research Assistant, for the times when you need additional help.

Figure 1-3 Viewing API reference in the Documentation window

To display the API reference for a symbol in a source file, you select the symbol in the text editor and choose Help > Find Selected Text in API Reference (you can also Option–double-click the symbol name). This command searches for the selected symbol in the API reference for your project’s SDK and displays it in the Documentation window. For example, if you select the UIFont class name in a source file and execute the Find Selected Text in API Reference command, Xcode opens the Documentation window and displays the API reference for the UIFont class.

While the Documentation window is a great tool to browse the iPhone documentation library, sometimes you may not want to take your focus away from the text editor while you write code, but need basic information about a symbol in a condensed way. The Research Assistant provides such information in a small and unobtrusive window.

The Research Assistant actively follows you as you move the cursor around a source file. When it recognizes a symbol for which it finds API reference, the Research Assistant displays that reference, as shown in Figure 1-4. All you have to do is glance at the Research Assistant to get essential details about the symbol.

To display the Research Assistant, choose Help > Show Research Assistant.

Figure 1-4 Viewing API reference in the Research Assistant

Text editor with the cursor over the text  “UIFont systemFontOfSize:(CGFloat)fontSize”. Research Assistant with API  reference for the systemFontOfSize: method of the UIFont class.Text editor with the cursor over the  text “UIFont systemFontOfSize:(CGFloat)fontSize”. Research Assistant  with API reference for the systemFontOfSize: method of the UIFont  class.

From the Research Assistant you can quickly jump to more comprehensive reference for the symbol, or even view the header that declares it.

For more information about accessing documentation in Xcode, see Documentation Access.

Building and Running Your Application

iPhone Simulator implements the iPhone OS API, providing an environment that closely resembles the environment devices provide. It allows you to run your applications in Mac OS X, letting you quickly test application functionality when you don’t have a device available. However, running applications in iPhone Simulator is not the same as running them in actual devices. iPhone Simulator does not emulate device performance: It doesn’t implement the memory constraints or processor performance of an actual device. First, the simulator uses Mac OS X versions of the low-level system frameworks instead of the versions that run on the devices. Secondly, there may be hardware-based functionality that’s unavailable on the simulator. But, in general, the simulator is a great tool to perform initial testing of your applications.

To get an accurate idea of how your application performs on a user’s device, you must run the application on a device and gather performance data using Instruments and other performance-measuring tools.

To compile and debug your code, Xcode relies on open-source tools, such as GCC and GDB. Xcode also supports team-based development with source control systems, such as Subversion, CVS, and Perforce.

Building your application involves the following steps:

  • Compiling your source files and generating your application binary.

  • Placing the binary in iPhone Simulator or on your device.

Xcode performs these tasks for you when you execute the Build command. See “Running Applications” for details.

Measuring Application Performance

After you have tested your application’s functionality, you must ensure that it performs well on a device. This means that the application uses the device’s resources as efficiently as possible. For example, memory is a scarce resource; therefore, your application should maintain a small memory footprint not to impair the performance of iPhone OS. Your application should also use efficient algorithms to consume as little power as possible not to reduce battery life. Xcode provides two major tools to measure and tune application performance: Instruments and Shark.

The Instruments application is a dynamic performance analysis tool that lets you peer into your code as it’s running and gather important metrics about what it is doing. You can view and analyze the data Instruments collects in real time, or you can save that data and analyze it later. You can collect data about your application’s use of the CPU, memory, the file system, and the network, among other resources.

The Shark application is another tool that helps you find performance bottlenecks in your code. It produces profiles of hardware and software performance events and shows how your code works as a whole and its interaction with iPhone OS.

See “Tuning Applications” for more information.

Further Exploration

To learn more about the Xcode development process, see A Tour of Xcode.

Tutorial: Hello, World!

This tutorial guides you through the creation of a simple project that prints text on the iPhone screen.

Create the Project

To create the Hello World project, follow these steps:

  1. Launch the Xcode application, located in /Applications.

    represents the directory in which you installed the Xcode toolset. See “Xcode Installation Details” for more information.

  2. Choose File > New Project.

  3. Select the Window-Based Application template and click Choose.

    New Project dialog with iPhone OS Application template group  selected and six iPhone project templates shown. The  Window-based–Application template is selected, with “Use Core Data for  storage” option selected. A description of the template is also  displayed.
  4. Name the project HelloWorld and choose a location for it in your file system.

  5. Add the MyView class to the project.

    1. Choose File > New File.

    2. Select the Cocoa Touch UIView subclass template and click Next.

      New File dialog with iPhone OS Cocoa Touch Class template group  selected, and the Objective-C–class template selecteds. The options of  the “Subclass of” pop-up menu are displayed; the UIView option is  highlighted.
    3. In the File Name text field, enter MyView.m.

    4. Select the “Also create "MyView.h"” option and click Finish.

  6. Choose the active SDK for your project.

    If you have a development device plugged in at the time you create the project, Xcode sets the active SDK to build for your device. Otherwise, it sets it to build for iPhone Simulator.

    Note: To use the iPhone Device SDK you must be a member of the iPhone Developer Program. For more information, see “Accessing the iPhone Developer Program Portal.”

    To set the active SDK, chose an item from the Project > Set Active SDK submenu or the Overview toolbar menu in the project window.

    Project window with Overview toolbar item  disclosed showing the “active” settings for the project.Project window with Overview toolbar  item disclosed showing the “active” settings for the project.

Write the Code

The Xcode text editor is where you spend most of your time. You can write code, build your application, and debug your code. Let’s see how Xcode assists you in writing code.

To experience the Xcode source-code editing features, you should perform the following instructions to enter the application’s source code. For your convenience, “Hello, World! Source Code” includes the final source code.

First, modify the HelloWorldAppDelegate class to use the MyView class:

  1. In the Groups & Files list, select the HelloWorld group.

  2. In the detail view, double-click HelloWorldAppDelegate.m.

  3. In the HelloWorldAppDelegate editor window:

    1. Add the following code line below the existing #import line.

      #import "MyView.h"
    2. Add the following code lines to the applicationDidFinishLaunching: method, below the override-point comment.

      MyView *view = [[MyView alloc] initWithFrame:[window frame]];
      [window addSubview:view];
      [view release];

After making these changes, the code in the HelloWorldAppDelegate.m file should look like this:

#import "HelloWorldAppDelegate.h"
#import "MyView.h"
 
@implementation HelloWorldAppDelegate
 
@synthesize window;
 
- (void)applicationDidFinishLaunching:(UIApplication *)application {
 
   // Override point for customization after app launch
   MyView *view = [[MyView alloc] initWithFrame:[window frame]];
   [window addSubview:view];
   [view release];
 
   [window makeKeyAndVisible];
}
 
- (void)dealloc {
    [window release];
    [super dealloc];
}
 
@end

Listing 1-1 shows the code that draws “Hello, World!” in the window. Add the highlighted code lines to the drawRect: method in the MyView.m file.

Listing 1-1 Method to draw “Hello, World!” in a view

- (void) drawRect:(CGRect) rect {
    NSString *hello   = @"Hello, World!";
    CGPoint  location = CGPointMake(10, 20);
    UIFont   *font    = [UIFont systemFontOfSize:24.0];
    [[UIColor whiteColor] set];
    [hello drawAtPoint:location withFont:font];
}

If you turned on code completion (as described in “Using Code Completion”), as you type symbol names the text editor suggests completions for the symbol names it recognizes. For example, as you type CGPointM, the text editor suggests the completion shown in Figure 1-2. You can take advantage of completion here by accepting the suggested completion and jumping to the parameter placeholders:

  1. Jump to the first parameter by choosing Edit > Select Next Placeholder, and type 10.

    The Select Next Placeholder command moves you among the arguments in function or method calls that the text editor suggests as completions to the text you’re typing.

  2. Jump to the second parameter and type 20.

  3. Enter the semicolon (;) at the end of the line and press Return.

Run the Application

To build and run the Hello World application, choose Build > Build and Run (or click the Build and Go toolbar item in the project window). If there are no build errors, Xcode installs the application in iPhone Simulator or your device (depending on the active SDK setting).

iPhone Simulator with the “Hello, World!” white text on a black  background on its screen.

Troubleshooting Hello, World! Build Errors

This section contains possible build errors for the Hello, World! project and their cause.

Building ... — 2 errors
   Compiling /Classes/HelloWorldAppDelegate.m (2 errors)
      error: 'MyView' undeclared (first use in this function)
      error: 'view' undeclared (first use in this function)

Fix this build error by adding the line

#import "MyView.h"

to the HelloWorldAppDelegate.m file.

To learn about other possible build errors, see “Solving Build Errors.”

Tuesday, May 18, 2010

Basic Object Oriented Programming (OOP) Concept

Objects:

As the name object-oriented implies, objects are key to understanding object-oriented technology. You can look around you now and see many examples of real-world objects: your dog, your desk, your television set, your bicycle.
These real-world objects share two characteristics: they all have state and they all have behavior. For example, dogs have state (name, color, breed, hungry) and dogs have behavior (barking, fetching, and slobbering on your newly cleaned slacks). Bicycles have state (current gear, current pedal cadence, two wheels, number of gears) and behavior (braking, accelerating, slowing down, changing gears).
Software objects are modeled after real-world objects in that they, too, have state and behavior. A software object maintains its state in variables and implements its behavior with methods.

Definition: An object is a software bundle of variables and related methods.

You can represent real-world objects using software objects. You might want to represent real-world dogs as software objects in an animation program or a real-world bicycle as a software object within an electronic exercise bike. However, you can also use software objects to model abstract concepts. For example, an event is a common object used in GUI window systems to represent the action of a user pressing a mouse button or a key on the keyboard.
The following illustration is a common visual representation of a software object:

Classes:

In the real world, you often have many objects of the same kind. For example, your bicycle is just one of many bicycles in the world. Using object-oriented terminology, we say that your bicycle object is an instance of the class of objects known as bicycles. Bicycles have some state (current gear, current cadence, two wheels) and behavior (change gears, brake) in common. However, each bicycle's state is independent of and can be different from other bicycles.
When building bicycles, manufacturers take advantage of the fact that bicycles share characteristics by building many bicycles from the same blueprint--it would be very inefficient to produce a new blueprint for every individual bicycle they manufactured.
In object-oriented software, it's also possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips and so on. Like the bicycle manufacturers, you can take advantage of the fact that objects of the same kind are similar and you can create a blueprint for those objects. Software "blueprints" for objects are called classes.


Definition: A class is a blueprint or prototype that defines the variables and methods common to all objects of a certain kind.

Objects vs. Classes
You probably noticed that the illustrations of objects and classes look very similar to one another. And indeed, the difference between classes and objects is often the source of some confusion. In the real world it's obvious that classes are not themselves the objects that they describe--a blueprint of a bicycle is not a bicycle. However, it's a little more difficult to differentiate classes and objects in software. This is partially because software objects are merely electronic models of real-world objects or abstract concepts in the first place. But it's also because many people use the term "object" inconsistently and use it to refer to both classes and instances.
In the figures, the class is not shaded because it represents a blueprint of an object rather than an object itself. In comparison, an object is shaded, indicating that the object actually exists and you can use it.


The Benefit of Classes
Objects provide the benefit of modularity and information hiding. Classes provide the benefit of reusability. Bicycle manufacturers reuse the same blueprint over and over again to build lots of bicycles. Software programmers use the same class, and thus the same code, over and over again to create many objects.

Data abstraction:

Abstraction is the process of recognizing and focusing on important characteristics of a situation or object and leaving/filtering out the un-wanted characteristics of that situation or object.Lets take a person as example and see how that person is abstracted in various situations
• A doctor sees (abstracts) the person as patient. The doctor is interested in name, height, weight, age,
blood group, previous or existing diseases etc of a person
• An employer sees (abstracts) a person as Employee. The employer is interested in name, age,
health, degree of study, work experience etc of a person.
So, you see that Abstraction is the basis for software development. Its through abstraction we define the essential aspects of a system. The process of identifying the abstractions for a given system is called as Modelling (or object modelling).
In the above example, the doctor may not be interested in characteristics of a person on which the employer is interested in and vice versa. Both employer and doctor will not be interested in all the characteristics of a person (like the color of dress the person wears on a particular day, the food the person takes, the relatives of the person etc). But however some elements are common to both doctor and the employer (like name, age, height etc). This common element gives way to generalization. Ie, if we eliminate enough details of an abstraction, it become so generalized that it can be applied wide in range of situations.One good example for such a generalization is a cell. A generalized cell would look like


Though the above generalized cell doesnt look like a brain cell or muscle cell, the above can still be used to represent all cell types that have this common features.
In real world, there are millions of abstractions possible and many are complex in nature. The complexities of abstractions are handled by systematically classifying and generalizing the abstractions based on some pre-defined criteria. This process is known as classification. Classification builds up a hierarchy and its called as abstract hierarchy. You can see an example of an abstract hierarchy below .

So, we see that abstraction is the basis for object oriented programming. Abstraction serves as the foundation for determining the classes for a particular system (which is called object model). But be advised, there is no acid test to decide if the abstraction for a given system is right or wrong. A "person" abstraction for a hospital information system would be different from a person abstraction for a library information system and even with hospital information system, person abstraction may be different for different projects.
Once you have abstracted an object, it can be re-used. It can be modified to suit other situations. As a child you learnt Tri-cycle. You used the experience of learning tri-cycle (handle bar control, pedaling) to learn bicycling. What actually you do to learn bicycling is that you only learn to balance the bicycle while you use the experience of tricycle to use handlebar and pedaling. The same case applies to abstraction as well.
Though abstraction seems to be a simple concept, it’s a challenging task. The reasons are
1. There are un-limited numbers of possibilities to define an abstraction for a situation.
2. As mentioned earlier, there is no acid test to determine if the abstraction is right or wrong. You end up discussing, arguing with your counter part that yours is best and his is worst…. He does the same thing…
However, these problems are always addressed as you gain experience (which you can gain by reading more books/articles and doing real time projects) in defining the abstraction. Abstraction by itself is a huge and an interesting concept. But, I feel that most of the people, who define classes, do it without knowing what an abstraction is. Most of the times they are right. But doing your work with more knowledge (knowing what you are doing) lets you to enjoy.
Note: Characteristics of a situation or object may be seen (legs of a table) or unseen (smell of a food), felt or unfelt. This means that there is no specific definition for characteristics of a situation or object..
Hope this article gives you an idea about Abstraction. Please feel free to post comments on what do you think about Abstraction.

Encapsulation:

Object diagrams show that an object’s variables make up the center, or nucleus, of the object. Methods surround and hide the object’s nucleus from other objects in the program. Packaging an object’s variables within the protective custody of its methods is called encapsulation.

Encapsulating related variables and methods into a neat software bundle is a simple yet powerful idea that provides two benefits to software developers:
• Modularity: The source code for an object can be written and maintained in- dependently of the source code for other objects. Also, an object can be easily passed around in the system. You can give your bicycle to someone else, and it will still work.
• Information-hiding: An object has a public interface that other objects can use to communicate with it. The object can maintain private information and meth- ods that can be changed at any time without affecting other objects that depend on it.

Polymorphism:

Polymorphism means that different objects respond distinctively to the same message. For example, when you send the same message, ‘cost’ to a spike-bicycle object, mono-cycle object and tandem bicycle object, each one responds appropriately. All of these cycles of the class bicycle have its own individual price.
Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. This means that a general class of operation may be accessed in the same manner even though specific actions associated with each operation may be accessed in the same manner even though specific actions associated with each operation may differ. Polymorphism is extensively used in implementing inheritance.
Polymorphism allows an entity (for example, variable, function or object) to take a variety of representations. Therefore we have to distinguish different types of polymorphism which will be outlined here.
The first type is similar to the concept of dynamic binding. The concept of dynamic binding allows a variable to take different types dependent on the content at a particular time. This ability of a variable is called polymorphism. Another type of polymorphism can be defined for functions. For example we will now look through the coding of C, suppose you want to define a function is Null () which returns TRUE if its argument is 0 (zero) and FALSE otherwise. For integer numbers this is easy:
boolean isNull(int i) {
if (i == 0) then
return TRUE
else
return FALSE
endif
}
However, if we want to check this for real numbers, we should use another comparison due to the precision problem:
boolean isNull(real r) {
if (r <> -0.99) then
return TRUE
else
return FALSE
endif
}
In both cases we want the function to have the name is Null. In programming languages without polymorphism for functions we cannot declare these two functions because the name is Null would be doubly defined. Without polymorphism for functions, doubly defined names would be ambiguous. However, if the language would take the parameters of the function into account it would work. Thus, functions (or methods) are uniquely identified by:
· The name of the function (or method) and
· The types of its parameter list.
Since the parameter list of both is Null functions differ, the compiler is able to figure out the correct function call by using the actual types of the arguments:
var i : integer
var r : real

i = 0
r = 0.0

...

if (isNull(i)) then ... /* Use isNull(int) */
...
if (isNull(r)) then ... /* Use isNull(real) */
If a function (or method) is defined by the combination of
· its name and
· the list of types of its parameters
we speak of polymorphism. This type of polymorphism allows us to reuse the same name for functions (or methods) as long as the parameter list differs. Sometimes this type of polymorphism is called overloading.
The last type of polymorphism allows an object to choose correct methods. Consider the function move() again, which takes an object of class Point as its argument. We have used this function with any object of derived classes, because there is-a relation holds.
Now consider a function display() which should be used to display draw able objects. The declaration of this function might look like this:
display(DrawableObject o) {
...
o.print()
...
}
We would like to use this function with objects of classes derived from Draw able Object:
Circle acircle
Point apoint
Rectangle arectangle

display(apoint) /* Should invoke apoint.print() */
display(acircle) /* Should invoke acircle.print() */
display(arectangle) /* Should invoke arectangle.print() */
The actual method should be defined by the content of the object o of function display(). Since this is somewhat complicated, here is a more abstract example:
class Base {
attributes:

methods:
virtual foo()
bar()
}

class Derived inherits from Base {
attributes:

methods:
virtual foo()
bar()
}

demo(Base o) {
o.foo()
o.bar()
}

Base abase
Derived aderived

demo(abase)
demo(aderived)
In this example we define two classes Base and Derived. Each class defines two methods foo() and bar(). The first method is defined as virtual. This means that if this method is invoked its definition should be evaluated by the content of the object.
We then define a function demo() which takes a Base object as its argument. Consequently, we can use this function with objects of class Derived as there is-a relation holds. We call this function with a Base object and a Derived object, respectively.
Suppose, that foo() and bar() are defined to just print out their name and the class in which they are defined. Then the output is as follows:
foo() of Base called.
bar() of Base called.
foo() of Derived called.
bar() of Base called.
Why is this so? Let's see what happens. The first call to demo() uses a Base object. Thus, the function's argument is filled with an object of class Base. When it is time to invoke method foo() it's actual functionality is chosen based on the current content of the corresponding object o. This time, it is a Base object. Consequently, foo() as defined in class Base is called.
The call to bar() is not subject to this content resolution. It is not marked as virtual. Consequently, bar() is called in the scope of class Base.
The second call to demo() takes a Derived object as its argument. Thus, the argument o is filled with a Derived object. However, o itself just represents the Base part of the provided object derived.
Now, the call to foo() is evaluated by examining the content of o, hence, it is called within the scope of Derived. On the other hand, bar() is still evaluated within the scope of Base.
Objects of super classes can be filled with objects of their subclasses. Operators and methods of subclasses can be defined to be evaluated in two contexts:
1. Based on object type, leading to an evaluation within the scope of the super class.
2. Based on object content, leading to an evaluation within the scope of the contained subclass.
The second type is called polymorphism.
In a word, Polymorphism means the sending of a message to an object without concern about how the software is going to accomplish the task, and furthermore it means that the task can be executed in completely different ways depending on the object that receives the message (in C++, polymorphism is implemented through the use of virtual functions). When the decision as to which actions are going to be executed is made at run-time, the polymorphism is referred to as late binding (as in the case of virtual functions). If they are made at compile time then it is known as early binding.

Inheritance:

Let's try to formalize the term ‘inheritance’:
Inheritance is the mechanism which allows a class A to inherit properties of a class B. We say A inherits from B. Objects of class A thus have accesses to attributes and methods of class B without the need to redefine them. The following definition defines two terms with which we are able to refer to participating classes when they use inheritance.
If class A inherits from class B, then B is called super class of A. A is called subclass of B. Objects of a subclass can be used where objects of the corresponding super class are expected. This is due to the fact that objects of the subclass share the same behavior as objects of the super class.
In the literature you may also find other terms for super class and subclass. Super classes are also called parent classes. Subclasses may also be called child classes or just derived classes.
Of course, you can again inherit from a subclass, making this class the super class of the new subclass. This leads to a hierarchy of super class/subclass relationships. If you draw this hierarchy you get an inheritance graph.
We've defined a class to be a definition, or blueprint, from which object oriented instances are created. A stereo is an instance of the stereo class. But classes themselves can be defined as specializations of other classes. For example, if you didn't know what a stereo was, you would probably understand if I told you that it was a hand held MP3 player. In fact, all handheld MP3 players share a certain number of characteristics. Like a stereo, a RIO can hold and play MP3 files downloaded from a computer. It can't hold as many songs as the stereo, but at least some of the functionality is the same. Hence the RIO is a subclass of the super class stereo or RIO is inherited from the class stereo.
A common drawing scheme is to use arrowed lines to indicate the inheritance relationship between two classes or objects. In our examples we have used “inherits-from”. Consequently, the arrowed line starts from the subclass towards the super class as illustrated below-

Inheritance means that the language gives you the ability to extend or enhance existing objects. The inherited class i.e. new class will have the combined features of both of the classes.
Let us review the whole thing again since it is perhaps the most important topic in OOP. Generally speaking, objects are defined in terms of classes. You know a lot about an object by knowing its class. Even if you don't know what a penny-farthing is, if I told you it was a bicycle, you would know that it had two wheels, handle bars, and pedals.
Object-oriented systems take this a step further and allow classes to be defined in terms of other classes. For example, mountain bikes, racing bikes, and tandems are all kinds of bicycles. In object-oriented terminology, mountain bikes, racing bikes, and tandems are all sub class of the bicycle class. Similarly, the bicycle class is the super class of mountain bikes, racing bikes, and tandems. This relationship is shown in the following figure.

Each subclass inherits state (in the form of variable declarations) from the super class. Mountain bikes, racing bikes, and tandems share some states: cadence, speed, and the like. Also, each subclass inherits methods from the super class. Mountain bikes, racing bikes, and tandems share some behaviour: braking and changing pedalling speed, for example.
However, subclasses are not limited to the state and behaviors provided to them by their super class. Subclasses can add variables and methods to the ones they inherit from the super class. Tandem bicycles have two seats and two sets of handle bars; some mountain bikes have an extra set of gears with a lower gear ratio.
Subclasses can also override inherited methods and provide specialized implementations for those methods. For example, if you had a mountain bike with an extra set of gears, you would override the "change gears" method so that the rider could use those new gears.
You are not limited to just one layer of inheritance. The inheritance tree, or class hierarchy, can be as deep as needed. Methods and variables are inherited down through the levels. In general, the farther down in the hierarchy a class appears, the more specialized is its behavior.
The Object class is at the top of class hierarchy, and each class is its descendant (directly or indirectly). A variable of type Object can hold a reference to any object, such as an instance of a class or an array. Object provides behaviors that are required of all objects running in the Java Virtual Machine. For example, all classes inherit Object's to String method, which returns a string representation of the object.
Inheritance offers the following benefits:
· Subclasses provide specialized behaviours from the basis of common elements provided by the super class. Through the use of inheritance, programmers can reuse the code in the super class many times.
· Programmers can implement super classes called abstract classes that define "generic" behaviours. The abstract super class defines and may partially implement the behaviour, but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses.
One important object-oriented mechanism is multiple inheritance. Multiple inheritance does not mean that multiple subclasses share the same super class. It also does not mean that a subclass can inherit from a class which itself is a subclass of another class.
Multiple inheritances mean that one subclass can have more than one super class. This enables the subclass to inherit properties of more than one super class and to ``merge'' their properties. The following is an example of deriving a draw able string which inherits properties of Point and String. This ‘DrawableString’ is an example of multiple inheritance that inherits from ‘Point’ and ‘String’.
Messages/ Message passing:

A single object alone is generally not very useful and usually appears as a component of a larger program or application that contains many other objects. Through the interaction of these objects, programmers achieve higher order functionality and more complex behavior. Your bicycle hanging from a hook in the garage is just a bunch of titanium alloy and rubber; by itself the bicycle is incapable of any activity. The bicycle is useful only when when another object (you) interacts with it (starts pedaling).
Software objects interact and communicate with each other by sending messages to each other. When object A wants object B to perform one of B's methods, object A sends a message to object B.
Sometimes the receiving object needs more information so that it knows exactly what to do--for example, when you want to change gears on your bicycle, you have to indicate which gear you want. This information is passed along with the message as parameters.
Three components comprise a message:
1. The object to whom the message is addressed (Your Bicycle)
2. The name of the method to perform (changeGears)
3. Any parameters needed by the method (lower gear)
These three components are enough information for the receiving object to perform the desired method. No other information or context is required.
The Benefits of Messages
• An object's behavior is expressed through its methods, so (aside from direct variable
access) message passing supports all possible interactions between objects.
• Objects don't need to be in the same process or even on the same machine to send and
receive messages back and forth to each other.









Monday, May 17, 2010

what is Objective-C?

Objective-C is a reflective, object-oriented programming language which adds Smalltalk-style messaging to the C programming language.

The Objective-C language is a simple computer language designed to enable sophisticated object-oriented programming. Objective-C is defined as a small but powerful set of extensions to the standard ANSI C language. Its additions to C 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, and to do so in a simple and straightforward way.

Most object-oriented development environments consist of several parts:

* An object-oriented programming language

* A library of objects

* A suite of development tools

* A runtime environment