free intro to iphone programming ebook

34
Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved Beginning Your iPhone Programming Journey An Introductory Chapter from EDUmobile.ORG iPhone Development Training Program

Upload: iphonehead

Post on 12-Jan-2015

2.847 views

Category:

Technology


0 download

DESCRIPTION

Many experts agree that EDUmobile's complete iPhone Programming course may be the best course online. Already, over 350 students have enrolled and are under training from over 50 countries worldwide! With this beginner-friendly ebook, you'll gain a basic understanding of iPhone Programming and see a walkthrough of a simple Hello World App. This book has 34 pages of fantastic content that will walk you through some of the basics of iPhone Development and introduce you to the path you will have to take if you want to successfully start developing iPhone Apps that you can convert into cash! Sign up at the link below to get your free copy! http://www.edumobile.org/iphone-programming-ebook-free.php This is an Introductory Chapter from the highly popular EDUmobile iPhone Development Training Program.

TRANSCRIPT

Page 1: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Beginning Your iPhone Programming Journey

An Introductory Chapter from EDUmobile.ORGiPhone Development Training Program

Page 2: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

NOTICE: You Do NOT Have the Rightto Reprint or Resell This eBook!

You Also MAY NOT Give Away,Sell or Share the Content Herein

Copyright © 2009 – 2010 EDUmobile.ORG

ALL RIGHTS RESERVED.

No part of this ebook may be reproduced or transmitted in any form whatsoever,electronic, or mechanical, including photocopying, recording, or by any informationalstorage or retrieval system without the expressed written, dated and signedpermission from the author.

LIMITS OF LIABILITY / DISCLAIMER OF WARRANTY

The authors and publisher of this book have used their best efforts in preparing thismaterial. The authors and publisher make no representation or warranties withrespect to the accuracy, applicability, fitness, or completeness of the contents of thisprogram.

They disclaim any warranties (expressed or implied), merchantability, or fitness forany particular purpose. The authors and publisher shall in no event be held liable forany loss or other damages, including but not limited to special, incidental,consequential, or other damages.

This manual contains material protected under International and Federal Copyrightlaws and Treaties. Any unauthorized reprint or use of this material in prohibited.

Page 3: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Beginning Your iPhone Programming Journey

Every once in a while a new opportunity arises due to a revolutionarytechnology and business model which is years ahead of the current scenario.

Apple has done exactly that with its iPhone and iPod products, content deliverymechanism and business model that has leveled the playing field between big,small and individual businesses.

Those of us who move quickly to learn the technology are the ones who willbenefit the most from it, before ideas are taken by others and before themarket gets too saturated, making it harder to succeed.

You may have a very exciting idea and a passion to learn the tricks of codinglike the gurus, but the due to limited iPhone development tutorials online andlack of well structured courses, your journey may probably not take off at all.As a result, your idea that could become the next blockbuster application onthe App Store – will never happen and remain just a dream.

And, its not really your fault… as there are currently no affordable onlineiPhone development courses that teach you through real tutors who guide youthrough step by step.

This is where the iPhone Course offered at EDUmobile.ORG comes in…

Over a period of 12 weeks you will learn the topics step by step and startcoding like the iPhone gurus. We will teach you through the following mediums -

Weekly Online Videos that you can download and view at your convenience

Access to Real Tutors to help you solve coding or conceptual issues, on aone-on-one basis

Weekly Worksheets and Exercise for you to do with challenging examplesthat are set up with just the right learning curve

Access to an Online Form for discussing issues and meeting other students.

One or Two Live industrial projects at the end of the course

Plus you get a full 30 days no questions asked full money back guarantee.

All this said, now lets get started …

Page 4: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

First things first… is the iPhone Programming Courseright for me?

Before starting your journey, you must understand what is needed andexpected of you to finish the course successfully.

If you have absolutely no knowledge of programming, it will be very hard –although not impossible. Since, this is a programming course, you will be betterprepared if you have programmed before – in any language.

It does not matter if you programmed in Java, C or Scripted websites. As longas you know the basics you are good to go.

However if you are not a programmer, but are up to the challenge, then youmust ask yourself if you will be programming yourself - or will you go throughthis course to eventually become a producer for an iPhone product.

All said - a very basic knowledge of programming is a must.

I suggest that you try to learn just basic C or python to quickly learn theprogramming nuances and concepts.

If you are from a completely non-programming background, you may need aweek to 1 month to catch up with the basics depending on the time you spendon learning.

So, in order to get started comfortably with this course, you should be able tounderstand the following concepts before you go forward -

What are data types?

What are operators?

What are conditionals?

What are loops?

What are arrays and strings?

What are objects?

What are methods?

Page 5: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

I’ll stop at that, for now. This should be more than enough.

I suggest you know at least a few of the above, if not all, and they should notsound completely alien to you! Of course, if you need to review some of theseconcepts, you can continue brushing up your programming fundamentals inparallel to the iPhone course.

Either way … you need to do some homework before you start the iPhoneProgramming course!

Page 6: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

How is the Course Structured?

The iPhone Course is structured to teach you and focus on the following -

Objective C

Cocoa Touch Framework

iPhone SDK

iPhone APIs

Objective C

Objective C is a programming language which will be used to program on theiPhone. If you have programmed for Mac before you already know Objective Cand for those who are new Objective C you can think Objective C to be child ofC programming language and a distant cousin of C++.

It was developed by Brand Cox and Tom Love for their company StepStone.According to Wikipedia Objective-C is a reflective, object-orientedprogramming language, which adds Smalltalk-style messaging to the Cprogramming language. Now if you don’t understand what is reflective, objectoriented and messaging there is no need to panic.

It will be discussed soon and you will cross these mole hills before you actuallyclimb the mountain.

Cocoa Touch Framework

Cocoa touch is Apple's name for the collection of frameworks, APIs, andaccompanying runtimes that make up the development layer of iPhone OS.

By developing with the Cocoa touch frameworks you will be writing applicationsthe same way that iPhone OS itself is written, with controlled access to the theoperating system. You need to learn various aspects of the touch framework tomaster the iPhone programming.

Page 7: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

iPhone SDK

The iPhone SDK consist primarily of Xcode and Interface Builder. The Xcode isall season complete SDK for building MAC software. It has been extended tosupport the iPhone and iPod programming.

The other tool that will be used very often is called the interface builder. Ithelps creating faster interface for your application with minimal coding thusreducing the development time considerably.

iPhone APIs

Additionally to Cocoa there are other libraries such as OpenGL es which youneed to learn to give your application that extra punch which can knock downthe competition.

The other iPhone specific components that you need to learn is SQLite , Coreanimation, Accelerometer, phone and media playing APIs.

Page 8: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Understanding The iPhone SDK

The first thing we need to do to get started is to setup our coding environmenton our computer.

For this, we need to download and install the iPhone SDK on our Mac or theVirtual OS on our Windows PC.

Installing the SDK

Download the SDK from http://developer.apple.com/iphone after registeringat the portal. The registration is free. If you want, you can optionally join thedeveloper program for $99 only, but we suggest you do that later.

Once the Xcode is installed, it will appear in the dock as shown below. Youneed to click and start the Xcode to create your first application.

Alternatively, you can search for Xcode in Finder and can start things fromthere.

Page 9: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Once Xcode is started, the following screen will be visible on your desktop…

Now, close the smaller window, and you are ready to start programming foriPhone!

Next, do the following…. Access –

File >> New Project

… and a new project template window will be displayed as shown on the nextpage, below -

Page 10: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Page 11: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

You will see that there are ready made templates for creating applications.

These templates are handy to use and more often than not, we will usestandard templates to create our applications.

However, if you do not need any hand holding and you want to create anapplication from scratch, you may use the windows based application.

For our example today we will select …

“View Based Application”.

... and give a name to the Application as “Hello World” .

The following screens will appear…

Page 12: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

However, before we start any work on our application we need to familiarizeourselves with the Xcode IDE.

So what exactly is Xcode IDE ?

Xcode IDE primarily can be narrowed down to three major parts in addition tothe Menu. They are …

The Top Bar

The Side bar

The code editor

Page 13: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

1. The Top Bar

This customizable bar provides shortcuts to menu elements, and looks likethis…

2. The Side Bar

This bar displays the directory structure of the current project. We will use itmore in a later part of our course. It looks like this …

Page 14: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

3. The Code Editor

The other major part is the code editor. The content area is where you writeyour code. You can access the files from the side bar by clicking them and itwill show up in the content window.

Page 15: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Application Architecture - A Sample Application

When we created the views based project, Xcode create lots of code andcomponent for us. Let us have a detailed look into this code.

If we click on the Classes folder on the left panel we will see the classes thathave been created by the Xcode.

These classes are…

Hello_WorldAppDelegate.h

Hello_WorldAppDelegate.m

Hello_WorldViewController.h

Hello_WorldViewController.m

These are all Objective C files, each playing a designated role in the project.

Through in this article we will not get into the details of these files but, forclarity of purpose, we will define the work assigned to these classes.

We know that “.h” files in objective C are for deceleration and “.m” files havethe implementation details. So the two classes Delegate and View Controllerare also divided into respective “.h” and “.m” files.

The Delegate class is the class which listens to the Applications running. Thisclass actually starts the application and exists all through the life cycle of theapplication.

In short you can consider the Delegate as the Shell which enables theapplication. Application passes messages on to the delegate through its lifecycle which is handled and acted upon by it.

The View Controller is very specific to view based application that we haveselected. Before we discuss the View Controller we must tell you that View isnecessary to draw content on the iPhone.

In fact each iPhone Application has one window and can have multiple views. Aview is drawn over a window and in most of our practical applications we willbe dealing with views only.

Page 16: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

A view is something that is visible to user and the controller decides whatshould be shown on the view.

This architecture is similar to the MVC architecture where we use model viewand controller components to create our application.

Auto Generated Code Example

Let us now have a detail look into the code generated by the Xcode. In orderfor it to make any sense you must understand ObjectiveC.

However, even if you are not familiar with this, as of now, you can readthrough it. We have briefly clarified most of the major concepts.

Before we look into the code let us just do a bit of Objective C.

Objective C is Objects added to C. It is quite different from C++ in terms of itssyntax and is rather similar to Smalltalk. However, it contains most of theobject oriented features like Data Encapsulation, Polymorphism andInheritance.

Now, let us talk about some important concepts which are there is the codebelow

@interface - The interface in objective C is use to declare the methods anddata elements of the class.

@implementation - The implementation defines the methods that weredeclared earlier using the interface.

@class - Declares the methods defined elsewhere. It is less memory intensivethan an #import statement and in a compact device like iPhone it will usedmore often than mac applications.

@property and @synthesize - The property and synthesize directive addgetter and setter function to the class. A getter and setter function is use toassign and obtain values to an object. When we use @synthesize we do nothave to explicitly define a get and set function for the object properties it justget internally defined by the system.

Page 17: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

IBOutlet - It is a special instance variable that references another object. Itlets the Interface builder know of the object. We will discuss it in detail inlater weeks.

IBAction - It is the trigger which is called from an Interface builder UI object.

Now that you are familiar with the above concepts, here is the code snippet…

AppDelegate.h

@class Hello_WorldViewController;

@interface Hello_WorldAppDelegate : NSObject <UIApplicationDelegate> {UIWindow *window;Hello_WorldViewController *viewController;

}

@property (nonatomic, retain) IBOutlet UIWindow *window;@property (nonatomic, retain) IBOutlet Hello_WorldViewController *viewController;

@end

Explanantion of the code above…

The Above delegate class starts with defining a class directive for viewcontroller.

As discussed above it does that to import the definitions from view Controllerclass. The Next line uses a concept called as Protocol -

@interface Hello_WorldAppDelegate : NSObject <UIApplicationDelegate>

A protocol is list of methods shared between classes.

UIApplicationDelegate is the protocol and the NSObject is the parent class ofHello_WorldAppDelegate.

Page 18: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Next, we create object of UIWindow and View controller.

Then, we make these objects properties.

The key words “nonatomic” and “retain” decides the way the object is storedand accessed. We will talk about them a bit later.

This concludes our explanation of AppDelegate.h code.

Now, lets Move on to our Second code example

AppDelegate.m

#import "Hello_WorldAppDelegate.h"#import "Hello_WorldViewController.h"

@implementation Hello_WorldAppDelegate

@synthesize window;@synthesize viewController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {

// Override point for customization after app launch [window addSubview:viewController.view]; [window makeKeyAndVisible];}

- (void)dealloc { [viewController release]; [window release]; [super dealloc];}

@end

Page 19: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Explanantion of the code above

We know that .m file is the implementation file.

We start by importing the “.h” files. This is required for the compiler torelate the objects to the corresponding class.

We then synthesize the two properties we created earlier. Please note wewill have to synthesize any properties before using them.

We then find a method which is first called as soon as the application starts.The method “ applicationDidFinishLaunching” is created automatically theSDK. This starts the application with the root window.

It then adds the view on top of the window with the key word“addSubview”.

As our view is being handled by the object viewController the system addedaddSubview:viewController.view.

The next method dealloc is to free the memory occupied by the objects wecreated.

Third Code Example Snippet

ViewController.h

#import <UIKit/UIKit.h>

@interface Hello_WorldViewController : UIViewController {

}

@end

Explanantion of the code above

Currently this class has very few lines and it just declares itself as aninterface.

Page 20: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Fourth Code Example

ViewController.m

#import "Hello_WorldViewController.h"

@implementation Hello_WorldViewController

////Some methods

- (void)didReceiveMemoryWarning {// Releases the view if it doesn't have a superview.

[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.}

- (void)viewDidUnload {// Release any retained subviews of the main view.// e.g. self.myOutlet = nil;

}

- (void)dealloc { [super dealloc];}

@end

Explanantion of the code above …

Currently the code is not doing much except for being an emptyimplementation file.

The methods that are there are empty and does not serve any purpose as ofnow. We will now take this program to the next level adding an interface toour application and we will do it by using Interface Builder.

Page 21: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Though it is possible to add interfaces without using Interface builder bydirectly using the objective C code, but it greatly simplifies the developmentprocess and reduces the time to a greater extent. Also, the aim of this articleis to make you familiar with IB - and so we will create our interface withinterface builder.

The “Interface Builder”

This is the interface creating utility that comes with Xcode for developinginterfaces.

To see it in action, in your side bar click the resources folder and click on theViewController.xib file.

The xib file is an interface file which is called a “nib file”. Once you doubleclick on the nib file it will automatically open the interface builder.

You will see the following on your screen…

The Interface builder has three main parts, namely -

Page 22: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

1. Component Window

This shows the components of the interface. In our example we have…

The File’s Owner, First Responder and View, explained in a nutshell…

At this point of time you can consider these element as components by whichthe interface is created and rendered on a device. The File owner is the masterclass and the interface we creates belong to the File Owner. The FirstResponder is responsible of responding to user inputs done at the interface. Wewill deal with them in detail in our later sections. The View is the actualinterface that will be visible to the user.

Page 23: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

2. Library

The library is the collection of interface elements like Label, TextBox andeven view controllers. You can create great applications just by using thesestandard components.

Page 24: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

3. Inspector

The inspector is the other major component of the interface builder. Itallows the developer to change various attributes of the interface object.

Using the Inspector we can change the following attributes -

View Attribute

Connection Attribute

Size attribute

Identity attribute.

Page 25: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

If you want to have a look at these attributes, select the Inspector from theDrop down menu and the window will appear in your screen.

Then, select View and the Inspector window will show different attributesfor each tab as listed above.

We will learn to use this a little later. We will first complete our applicationwhich will print “Hello World” on the window.

Completing the Application

Open the library from the Xcode menu.

Go to the element label and drag it to the view window which is currentlygray in color.

You will see the following ...

Page 26: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Once your label is present on the view, you can clearly see the word “Label”written on the view.

Moving forward, our task is to now convert this label to “Hello World”.

And… that is done very easily!

Simply double click on label and you can edit it to whatever you want.

Alternatively you can select the label and open up the Inspector. In viewattribute, that is first tab itself, change the text from label to Hello World.

Save the nib file and close the nib file by closing the component window.

So, now that we are done, we want to execute the first program we wrote!

In your Xcode top bar, click “Build and Run” and if everything is proper, youwill see the emulator appear and display the text… “Hello World” on thescreen, just as shown in the figure below…

Wasn’t that hard, was it ?

Page 27: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Lets Move on to our Next Exercise

As we have now successfully created our first Application we will try to extendthis application and will try and add a user event to it.

To do this, we will have to augment the code created by Xcode.

What we want to do is to insert a button in the interface which can be clickedby the user, and we should be able to change the message, as per the click.

We will start by creating an IBOutlet for the label which we want to changeand an IBAction to interpret the user action.

Make the following changes to Hello_WorldViewController.h

#import <UIKit/UIKit.h>

@interface Hello_WorldViewController : UIViewController {IBOutlet UILabel *label;

}

@property (nonatomic, retain) IBOutlet UILabel *label;

-(IBAction)buttonPressed;

@end

The code above creates an Outlet of class UILabel to store the label objectwhich has been defined as *label.

We then make this object a property to automatically use getter and setterfunctions later.

We then create a -(IBAction) buttonPressed trigger which will be calledwhen user presses the button element on the screen.

We now move on to the Interface builder, to create the necessary interface.

Page 28: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Double click the view controller nib file to open the interface builder.

Open the library and drag a round rectangle button from the library to getthe following view…

Click on the button and change the name to switch.

Now, we will associate this label with our UILabel object.

Control drag from the File Owner to the Label which is now written as “HelloWorld” and from the pop up that appears select “label”. “label” was theobject we created in our code.

Page 29: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Refer to the two images below -

Page 30: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Once our IBOutlet for label is set we will move to add the IBAction tobutton.

To connect the IBAction we will select the button and open up the Inspector.

Go to the connection attributes and drag “Touch up inside” to the FileOwner.

Select the action “buttonPressed” from the pop up.

If the connection is successfully joined your Connection Inspector should looklike the following…

Page 31: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

Once this is done save your nib file and move on to the Xcode.

Now, open the Hello_WorldViewController.m file and add the followingcode…

#import "Hello_WorldViewController.h"

@implementation Hello_WorldViewController@synthesize label;

-(IBAction)buttonPressed{

if([label.text isEqualToString:@"World Hello"])label.text = @"Hello World";

elselabel.text = @"World Hello";

}- (void)didReceiveMemoryWarning {

// Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.}

- (void)viewDidUnload {// Release any retained subviews of the main view.// e.g. self.myOutlet = nil;

}

- (void)dealloc {[label release];

[super dealloc];}

@end

We start by synthesizing the label object.

In the IBAction method we apply a simple conditional to check the currentstring and then change the string based on the current stage.

This completes our Application which displays hello world and then changesitself based on the user command.

Page 32: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

The output should look like this …

Page 33: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

This concludes our introductory tutorial for iPhone Programming!

We hope you enjoyed it!

You may download the source code for the above project from the followinglink - http://edumobile.org/downloads/Sample.zip

So,,, What Next ?

This was a small step in our journey towards getting started with iPhonedevelopment. If you are interested in learning iPhone Development, we suggestyou sign up for our complete 12 Week iPhone Programming Course at the linkbelow. It comes with a full money back guarantee, so there is no risk at all.

Page 34: Free intro to iphone Programming eBook

Copyright © 2009 – 2010 EDUmobile.ORG All Rights Reserved

You will be assigned your own personal one-on-one tutor, whom you mayconsult any time with questions and problems you face.

The course is delivered over a period of 12 weeks via Online Video that youmay download and view at your convenience, along with material and WeeklyWorksheets.

You will also get access to our private forum where you can meet otherfellow iPhone developers.

Affiliates Join Our High Paying Affiliate Program and Make Tons Of Money!

Interested in promoting our Courses and making money?

Get instant $25 bonus for signing up!

Click Here to sign up for our Affiliate Program

Click Here To Learn More About The iPhone Course and To Enroll