You are on page 1of 50

T7: iPhone SDK: A Kick Start

Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Javier Gonzalez-Sanchez Tecnologico de Monterrey, Campus Guadalajara Guadalajara, Mexico javiergs@itesm.mx

Maria Elena Chavez-Echeagaray Tecnologico de Monterrey, Campus Guadalajara Guadalajara, Mexico mechavez@itesm.mx

Tutorial Presented at OOPSLA 2008


Copyright is held by the author/owner(s). OOPSLA08, October 1923, 2008, Nashville, Tennessee, USA. ACM 978-1-60558-220-7/08/10.

The Association for Computing Machinery


2 Penn Plaza, Suite 701 New York, New York 10121-0701 Copyright 2008 by the Association for Computing Machinery, Inc. (ACM). This compilation is copyright by ACM, however copyright for the individual papers is owned by the author/owner(s). Copying for personal or classroom, use is permitted. To copy otherwise, to republish, to post on servers or redistribute to lists, requests specific permission from the authors. Notice to Past Authors of ACM-Published Articles ACM intends to create a complete electronic archive of all articles and/or other material previously published by ACM. If you have written a work that has been previously published by ACM in any journal or conference proceedings prior to 1978, or any SIG Newsletter at any time, and you do NOT want this work to appear in the ACM Digital Library, please inform permissions@acm.org, stating the title of the work, the author(s), and where and when published.

Printed in the USA

Table of Contents

INSTRUCTOR BIOGRAPHIES

iv

AGENDA

OBJECTIVES OF THE COURSE

vi

iPHONE SDK: A KICK START INTRODUCTION iPHONE PLATFORM TOOLS FOR DEVELOPMENT OBJECTIVE-C LANGUAGE CREATING AN APPLICATION iPHONE IN ACTION REFERENCES

1 3 7 11 17 25 33 38

OOPSLA 2008 Tutorial

iii

Javier Gonzlez & Maria Elena Chvez

Instructors Biographies

Javier Gonzlez Snchez javiergs@itesm.mx Tecnolgico de Monterrey, campus Guadalajara. Av. General Ramn Corona 2514. Col. Nvo. Mxico. Zip. 45201. Zapopan, Jalisco, Mxico. Javier is professor at Tecnolgico de Monterrey, campus Guadalajara since January 2000 and program chair of B.S. Computer Science and Technology program since 2006. Javier got his master degree in Computer Science by Instituto Politcnico Nacional in Mexico. He is a developer, project leader and consultant, working with private companies and public institutions, making analysis, design, re-engineering and implantation of computational systems and web applications. Areas of interest: distributed and parallel computing, data bases, Web services, software architecture and modeling. Member of Association Computing Machinery (ACM) since 2002. His publications include topics in: anti-patterns, visual programming environments and distributed systems. He has been participating as speaker and workshop organizers in areas such as Java2 ME, Web development (php, J2ee), Software Architecture among others. More about him at www.javiergs.com

Maria Elena Chvez Echeagaray mechavez@itesm.mx Tecnolgico de Monterrey, campus Guadalajara. Av. General Ramn Corona 2514. Col. Nvo. Mxico. Zip. 45201. Zapopan, Jalisco, Mxico. Maria Elena (Helen) is full-time teacher at Tecnolgico de Monterrey, campus Guadalajara since January 2001. Helen got her master degree in Computer Sciences by Tecnolgico de Monterrey campus Guadalajara. Areas of interest: programming, software engineering, data bases and networking. Member of the Association Computing Machinery (ACM) since 2000. Participate as staff member at Object Oriented Programming, Systems, Languages, and Applications (OOPSLA) as staff member (volunteer) at '98, '99, '00, '01, '02, '05. She has participated as workshop organizer in different workshops in different conferences organized by the university.

OOPSLA 2008 Tutorial

iv

Javier Gonzlez & Maria Elena Chvez

Agenda

1. INTRODUCTION

2. iPHONE PLATFORM

3. TOOLS FOR DEVELOPMENT

4. OBJECTIVE-C LANGUAGE

5. CREATING AN APPLICATION

6. iPHONE IN ACTION

7. FINAL EXERCISE

OOPSLA 2008 Tutorial

Javier Gonzlez & Maria Elena Chvez

Objetives of the Course

iPhone is a pretty new device that involve several technologies (phone, video, audio, images, and web among others). This gadget, the best in 2007 year according to Times Magazine, has captive the interest of different types of users and created a new emerging market in various environments. Today thousands of programmers want to provide applications on the iPhone. Apple recently released the iPhone SDK (March 2008) toolkit. Using XCode 3.0 under Mac OS X 10.5 as our IDE, and Objective-C and iPhone API as our programming tools we will create iPhone applications (from basic to medium level), which finally can be, load into an iPhone. Well start with the classical Hello World and continue to develop applications using graphical user interfaces, handling multi-touch and detect motion, communication with web application, and different media. Through this tutorial, the attendee will:

Learn about iPhone software architecture.

Learn about iPhone Development tools and Objective-C programming languaje.

iPhone Application Framework

Graphics and Media Overview

User Interface Design and Key practices for iPhone Applications

Location, Acceleration, Orientation and System Information

Fundamentals of iPhone for Web Developers

OOPSLA 2008 Tutorial

vi

Javier Gonzlez & Maria Elena Chvez

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

iPhone SDK: a Kick start


Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Copyright is held by the author/owner(s). OOPSLA 2008, October 1923, 2008, Nashville, Tennessee, USA. ACM 978-1-60558-220-7/08/10.

Agenda
1. Introduction 2. iPhone platform 3. Tools for development 4. Objective-C language 5. Creating an application 6. iPhone in action 7. Final exercise 8. References

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

1 1

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

What is it ?
 iPhone is a pretty new device that involve several technologies (phone, video,
audio, images, and web among others). This gadget, the best in 2007 year according to Times Magazine, has captive the interest of different types of users and created a new emerging market in various environments. Today thousands of programmers want to provide applications on the iPhone. Apple recently released the iPhone SDK (March 2008) toolkit.

Our Objective
 Using XCode 3.0 under Mac OS X 10.5 as our IDE, and Objective-C and
iPhone API as our programming tools we will create iPhone applications (from basic to medium level) which finally can be load into an iPhone. Well start with the classical Hello World and continue to develop applications using graphical user interfaces, handling multi-touch and detect motion, communication with web application, and different media.

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

2 2

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Go ahead

Introduction
1

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

3 3

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

SDK
 The iPhone SDK includes the complete set of Xcode 3.1 tools, compilers,
frameworks, and documentation for creating applications for iPhone OS 2.0. These tools include the Xcode IDE, the Instruments analysis tool and the iPhone Simulator. With this software you can develop applications that run on the iPhone and iPod touch.

Developer Connection

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

4 4

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Install
1. Boot into a partition with the Mac OS X v10.5.3 installed. 2. Download the iPhone SDK software. 3. Double-click on iPhone SDK installer package. 4. Follow the instructions in the Installer. 5. To install Xcode 3.1 in a directory other than the default /Developer, you must specify a new <Xcode> directory name on the "Custom Install" pane; e.g. Xcode3.1.

 Select the folder icon under "Location" next to the "Developer Tools Essentials"
package name.

 Select "Other..." at the top of the pop-up.  Navigate to the location for the new <Xcode> folder. Select "New Folder".
9

Install
 Enter a folder name in the "New Folder" window; e.g. Xcode3.1. Select
"Create".

 Finally, select "Choose" in the "Install Xcode Tools" pane.


6. If you need to install Mac OS X 10.3.9 Support or WebObjects, you must select "Customize", and check those packages on the "Custom Install" panel. 7. Authenticate as the administrative user. The first user you create when setting up Mac OS X has administrator privileges by default.

Developer applications such as Xcode, Instruments, and Interface Builder are installed in <Xcode>/Applications.
10

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

5 5

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Uninstall

To uninstall Xcode developer tools on the boot volume along with the <Xcode> directory, from a Terminal window type: $ sudo <Xcode>/Library/uninstall-devtools --mode=all



If you just want to remove the underlying developer content on the boot volume, but leave the <Xcode> directory and supporting files untouched, from a Terminal window type: $ sudo <Xcode>/Library/uninstall-devtools --mode=systemsupport



If you just want to just remove the UNIX development support on the boot volume, but leave the <Xcode> directory and supporting files untouched, from a Terminal window type: $ sudo <Xcode>/Library/uninstall-devtools --mode=unixdev



Finally, to just uninstall the <Xcode> directory you can simply drag it to the trash, or from a Terminal window type: $ sudo <Xcode>/Library/uninstall-devtools --mode=xcodedir

11

Time to Work 1

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

6 6

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

iPhone Platform
2

Introduction
 iPhone Plataform comprises the operating system and technologies that you use to
run applications natively on iPhone and iPod touch devices and iPhone OS. Although it shares a common heritage and many underlying technologies with Mac OS X, iPhone OS was designed to meet the needs of a mobile environment, where users needs are slightly different. Existing Mac OS X developers will find many familiar technologies, but theyll also find technologies that are available only on iPhone OS, such as the Multi-Touch interface and accelerometer support.

 The iPhone SDK contains the code, information, and tools you need to develop,
test, run, debug, and tune applications for the iPhone OS. The Xcode tools have been updated to support development for the iPhone OS. In addition to providing the basic editing, compilation, and debugging environment for your code, Xcode also provides the launching point for testing your applications on an iPhone or iPod touch device. Xcode also lets you run applications in iPhone simulator, a platform that mimics the basic iPhone OS environment on your local Macintosh computer.

14

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

7 7

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Key Concepts
 iPhone SDK supports the creation of graphically-oriented applications that run
natively in iPhone OS.

 Take advantage of built-in hardware such as the accelerometers, camera, and


graphics hardware.

 All of the applications data is displayed in a single window. This has lead to the
creation of new views and controls that allow you to present your applications data in an organized manner.

 The event-handling model in iPhone OS also represents a significant departure


from traditional desktop applications. Instead of relying on the traditional mouse and keyboard events, iPhone OS introduces the idea of touch events.

 User experience
15

Architecture
 Layers

Cocoa Touch Media Core Services Core OS

16

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

8 8

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Layers
 Core OS and Core Services layers contain the fundamental interfaces for
iPhone OS, including those used for accessing files, low-level data types, Bonjour services, network sockets, and so on. These interfaces are mostly C based and include technologies such as:

 Core Foundation,  CFNetwork,  SQLite,  Access to POSIX threads,  UNIX sockets  Among others.

17

Layers
 Media layer contains the fundamental technologies used to support 2D and 3D
drawing, audio, and video. This layer includes the C-based technologies:

 OpenGL ES,  Quartz, and  Core Audio,  Core Animation, an advanced Objective-C based animation engine.

18

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

9 9

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Layers
 In the Cocoa Touch layer, most of the technologies use Objective-C. The
frameworks at these layers provide the fundamental infrastructure used by your application. For example:



the Foundation framework provides object-oriented support for collections, file management, network operations, and more. the UIKit framework provides the visual infrastructure for your application, including classes for windows, views, controls, and the controllers that manage those objects. Other frameworks at this level give you access to the users contact and photo information and to the accelerometers and other hardware features of the device.
19





Starting Point
 The starting point for any new project is the Cocoa Touch layer, and the UIKit
framework in particular.

 The higher-level frameworks make it easy to support standard system


behaviors with the least amount of effort on your part.

20

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

10 10

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Time to Work 2

Tools for Development


3

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

11 11

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Tools
 To develop applications for iPhone OS, you need a Mac OS X computer
running the SDK which include:

 Xcode  Interface Builder  Instruments

23

Xcode
 The focus of your development experiences is the Xcode application. Xcode is
an integrated development environment (IDE) that provides all of the tools you need to create and manage your iPhone projects and source files, build your code into an executable, and run and debug your code either in iPhone simulator or on a device.

 To create a new iPhone application, you start by creating a new project in


Xcode. A project manages all of the information associated with your application, including the source files, build settings, and rules needed to put all of the pieces together. The heart of every Xcode project is the project windows

24

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

12 12

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Xcode

25

Xcode
 Xcode comes with an advanced text editor, which supports features such as code
completion, syntax coloring, code folding (to hide code blocks temporarily), and inline annotations for errors, warnings, and notes. The build system in Xcode provides both appropriate default settings and the ability to customize the environment. And if you need documentation, the Research Assistant provides context-sensitive documentation while the Xcode documentation window lets you browse and search for information.

 When you build your application in Xcode, you have a choice of building it for
iPhone simulator or for a device. The simulator provides a local environment for testing your applications to make sure they behave essentially the way you want. After you are satisfied with your applications basic behavior, you can tell Xcode to build it and run it on an iPhone or iPod touch connected to your computer. Running on a device provides the ultimate test environment, and Xcode lets you attach the built-in debugger to the code running on the device.

26

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

13 13

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Xcode

27

Interface Builder

Interface Builder is the tool you use to assemble your applications user interface visually. Using Interface Builder, you assemble your applications window by dragging and dropping preconfigured components onto it. The components include standard system controls such as switches, text fields, and buttons, and also custom views to represent the views your application provides. After youve placed the components on the windows surface, you can position them by dragging them around, configure their attributes using the inspector, and establish the relationships between those objects and your code. When your interface looks the way you want it, you save the contents to a nib file, which is a custom resource file format.



The nib files you create in Interface Builder contain all the information that the UI Kit needs to recreate the same objects in your application at runtime. Loading a nib file creates runtime versions of all the objects stored in the file, configuring them exactly as they were in Interface Builder. It also uses the connection information you specified to establish connections between the newly created objects and any existing objects in your application. These connections provide your code with pointers to the nib-file objects and also provide the information the objects themselves need to communicate user actions to your code.

28

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

14 14

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Interface Builder

29

Instruments
 To ensure that you deliver the best user experience for your software, the

Instruments environment lets you analyze the performance of your iPhone applications while running in the simulator or on a device. Instruments gathers data from your running application and presents that data in a graphical display called the timeline. You can gather data about your applications memory usage, disk activity, network activity, and graphics performance. The timeline view can display all of the different types of information side by side, letting you correlate the overall behavior of your application, not just the behavior in one specific area. To get even more detailed information, you can also view the detailed samples that Instruments gathers.

 In addition to providing the timeline view, Instruments provides tools to help you

analyze your applications behavior over time. For example, the Instruments window lets you store data from multiple runs so that you can see whether your applications behavior is actually improving or whether it still needs work. You can save the data from these runs in an Instruments document and open them at any time.

30

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

15 15

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Instruments

31

Instruments

32

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

16 16

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Time to Work 3

Objective-C Language
4

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

17 17

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Objective-C
 The Objective-C language is a simple computer language designed to enable

sophisticated object-oriented programming. Objective-C extends the standard ANSI C language by providing syntax for defining classes, methods, and properties, as well as other constructs that promote dynamic extension of classes. The class syntax and design are based mostly on Smalltalk, one of the first object-oriented programming languages. information should help you learn the basic syntax of Objective-C. Many of the traditional object-oriented concepts, such as encapsulation, inheritance, and polymorphism, are all present in Objective-C. There are a few important differences, but those differences are called out in this article and more detailed information is available if you need it. to have at least a basic understanding of the associated concepts before proceeding. The use of objects and object-oriented constructs is fundamental to the design of iPhone applications, and understanding how they interact is critical to creating your applications.

 If you have programmed with object-oriented languages before, the following

 If you have never programmed using an object-oriented language before, you need

35

Files
Extension
.h

Source Type
Header files. Header files contain class, type, function, and constant declarations. Source files. This is the typical extension used for source files and can contain both Objective-C and C code. Source files. A source file with this extension can contain C++ code in addition to Objective-C and C code. This extension should be used only if you actually refer to C++ classes or features from your Objective-C code.

.m

.mm

36

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

18 18

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

#import
 When you want to include header files in your source code, you can use the
standard #include compiler directive but Objective-C provides a better way.

 The #import directive is identical to #include, except that it makes sure that the
same file is never included more than once.

 The Objective-C samples and documentation all prefer the use of #import, and
your own code should too.

37

Strings
 The NSString class provides an object wrapper for strings that has all of the
advantages you would expect, including built-in memory management for storing arbitrary-length strings, support for Unicode, printf-style formatting utilities, and more. Because such strings are used commonly though, Objective-C provides a shorthand notation for creating NSString objects from constant values. To use this shorthand, all you have to do is precede a normal, double-quoted string with the @ symbol, as shown in the following examples:

NSString* NSString* ];

myString = @Hello World\n"; anotherString = [

NSString stringWithFormat:@"%d %s", 1, @"String

38

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

19 19

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Note
 Cocoa Framework is derived from the NeXTSTEP and OPENSTEP
programming environments developed by NeXT in the late 1980s.

 Apple acquired NeXT in December 1996, and subsequently went to work on


the Rhapsody operating system that was supposed to be the direct successor of OPENSTEP.

 The OPENSTEP base of libraries and binary support was termed Yellow Box.
Rhapsody evolved into Mac OS X, and the Yellow Box became Cocoa.

 As a result, Cocoa classes begin with the acronym "NS" (standing either for the
NeXT-Sun creation of OPENSTEP, or for the original proprietary term for the OPENSTEP framework, NeXTSTEP): NSString, NSArray, etc.

39

Class
 The specification of a class in Objective-C requires two distinct pieces: the
interface and the implementation.

 The interface portion contains the class declaration and defines the instance
variables and methods associated with the class.

 The implementation portion contains the actual code for the methods of the
class.

 The class declaration always begins with the @interface compiler directive and
ends with the @end directive. Following the class name (and separated from it by a colon) is the name of the parent class. The instance (or member) variables of the class are declared in a code block that is delineated by braces ({ and }). Following the instance variable block is the list of methods declared by the class. A semicolon character marks the end of each instance variable and method declaration.

40

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

20 20

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Class
@interface MyClass : NSObject { int count; id data; NSString* name; } - (id)initWithString:(NSString *)aName; + (MyClass *)createMyClassWithString: (NSString *) aName @end

41

Class
@implementation MyClass - (id)initWithString:(NSString *) aName { if (self = [super init]) { count count = 0; data = nil; name = [aName copy]; return self; } } + (MyClass *)createMyClassWithString: (NSString *) aName { return [[[self alloc] initWithString:aName] autorelease]; } @end

42

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

21 21

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Methods
 A class in Objective-C can declare two types of methods: instance methods
and class methods.

 An instance method is a method whose execution is scoped to a particular


instance of the class. In other words, before you call an instance method, you must first create an instance of the class.

 Class methods, by comparison, do not require you to create an instance, but


more on that later.

 The declaration of a method consists of the method type identifier, a return


type, one or more signature keywords, and the parameter type and name information.

 The colon characters declare the presence of a parameter. If a method has no


parameters, you omit the colon after the first (and only) signature keyword. In this example, the method takes two parameters.
43

Methods
-(void)insertObject:(id)anObject atIndex:(NSUInteger)index [myArray insertObject:anObj atIndex:0];

 Method Type  Return Type  Signature keywords  Parameter Types  Parameter Names
44

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

22 22

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Propierties
 Properties are a convenience notation used to replace accessor method
declarations. Properties do not create new instance variables in your class declaration.

 They are simply a shorthand for defining methods that access existing instance
variables. Classes that expose instance variables can do so using the property notation instead of using getter and setter syntax. Classes can also use properties to expose virtual instance variablesthat is, pieces of data that are computed dynamically and not actually stored in instance variables.

 Practically speaking, properties reduce the amount of redundant code you have
to write. Because most accessor methods are implemented in similar ways, properties eliminate the need to provide a distinct getter and setter method for each instance variable exposed in the class. Instead, you specify the behavior you want using the property declaration and then synthesize actual getter and setter methods based on that declaration at compile time.

45

Propierties
@property BOOL flag; @property (copy) NSString* nameObject; //Copy the object during assignment. @property (readonly) UIView* rootView; // Create only a getter method.

myObject.flag = YES; CGRect viewFrame = myObject.rootView.frame;

46

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

23 23

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Protocols and Delegates



A protocol declares methods that can be implemented by any class. Protocols are not classes themselves. They simply define an interface that other objects are responsible for implementing. When you implement the methods of a protocol in one of your classes, your class is said to conform to that protocol. In iPhone OS, protocols are used frequently to implement delegate objects. A delegate object is an object that acts on behalf of, or in coordination with, another object. By example, the UIApplication class implements the required behavior of an application. Instead of forcing you to subclass UIApplication to receive simple notifications about the current state of the application, the UIApplication class delivers those notifications by calling specific methods of its assigned delegate object. An object that implements the methods of the UIApplicationDelegate protocol can receive those notifications and provide an appropriate response. The declaration of a protocol looks similar to that of a class interface, with the exceptions that protocols do not have a parent class and they do not define instance variables. In the case of many delegate protocols, adopting a protocol is simply a matter of implementing the methods defined by that protocol. There are some protocols that require you to state explicitly that you support the protocol, and protocols can specify both required and optional methods.
47

 

 

Time to Work 4

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

24 24

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Creating an Application
5

Introduction
 At a high level, the process for creating an iPhone application is similar to that
for creating a Mac OS X application.

 Both use the same tools and many of the same basic libraries. Despite the
similarities, there are also significant differences.

 An iPhone is not a desktop computer; it has a different purpose and requires a


very different design approach. That approach needs to take advantage of the strengths of iPhone OS and forego features that might be irrelevant or impractical in a mobile environment.

 The smaller size of the iPhone and iPod touch screens also means that your
application's user interface should be well organized and always focused on the information the user needs most.

50

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

25 25

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Steps
 Initializing the application  Displaying a window  Drawing custom content  Handling touch events  Performing animations
51

Project

52

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

26 26

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

main.m
int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; }

53

Application Delegate
  
One of the most important architectural details of your project is defining the application delegate object, which is instantiated from a class you provide in your project. The application delegate class declares its interface in a *.h file and defines its implementation in a *.m file. Once you have added these files to the project, you can use Interface Builder to designate the class as the application delegate. Interface Builder is a visual tool that you use to create and arrange views in a window, set up view hierarchies, configure each view's options, and establish relationships between the views and the other objects of your application. Because it is a visual tool, you perform all of these tasks by dragging components around a window surface. The result is an interactive version of your interface that you can see immediately and change in seconds. Interface Builder saves your user interface in a file known as a nib file, which is an archive of your application's object graph. To launch Interface Builder and see how the application delegate object's role is defined, double-click the *.xib file The *.xib file is the nib file that contains your application's window and defines the relationships among several important objects in your application, including the application delegate.

 

54

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

27 27

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Application Window

Every application is responsible for creating a window that spans the entire screen and for filling that window with content. Graphical applications running in iPhone OS do not run side-by-side with other applications. In fact, other than the kernel and a few low-level system daemons, your application is the only thing running after it is launched. What's more, your application should never need more than one windowan instance of the UIWindow class. In situations where you need to change your user interface, you change the views displayed by your window. Windows provide the drawing surface for your user interface, but view objects provide the actual content. A view object is an instance of the UIView class that draws some content and responds to interactions with that content. iPhone OS defines standard views to represent things such as tables, buttons, text fields, and other types of interactive controls. You can add any of these views to your window, or you can define custom views by subclassing UIView and implementing some custom drawing and event-handling code. The MoveMe application defines two such viewsrepresented by the MoveMeView and PlacardView classesto display the application's interface and handle user interactions. At launch time, the goal is to create the application window and display some initial content as quickly as possible. The window is unarchived from the MainWindow.xib nib file. When the application reaches a state where it is launched and ready to start processing events, the UIApplication object sends the delegate an applicationDidFinishLaunching: message. This message is the delegate's cue to put content in its window and perform any other initialization the application might require.





55

Application Window

- (void)applicationDidFinishLaunching:(UIApplication *)application { // Set up the view controller UIViewController *aViewController = [[UIViewController alloc] initWithNibName:@"MoveMeView" bundle:[NSBundle mainBundle]]; self.viewController = aViewController; [aViewController release]; // Add the view controller's view as a subview of the window UIView *controllersView = [viewController view]; [window addSubview:controllersView]; [window makeKeyAndVisible]; }
56

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

28 28

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Application Window
- (void)setUpPlacardView { // Create the placard view // calculates its own frame based on its image PlacardView *aPlacardView = [[PlacardView alloc] init]; self.placardView = aPlacardView; [aPlacardView release]; placardView.center = self.center; [self addSubview:placardView]; }

57

Drawing
- (void)drawRect:(CGRect)rect { [placardImage drawAtPoint:(CGPointMake(0.0, 0.0))]; CGFloat x = self.bounds.size.width/2 - textSize.width/2; CGFloat y = self.bounds.size.height/2 - textSize.height/2; CGPoint point; UIFont *font = [UIFont systemFontOfSize:fontSize]; [[UIColor blackColor] set]; point = CGPointMake(x, y + 0.5); [currentDisplayString drawAtPoint:point forWidth:(self.bounds.size.width-STRING_INDENT) withFont:font fontSize:fontSize lineBreakMode:UILineBreakModeMiddleTruncation baselineAdjustment:UIBaselineAdjustmentAlignBaselines]; [[UIColor whiteColor] set]; point = CGPointMake(x, y); [currentDisplayString drawAtPoint:point forWidth:(self.bounds.size.width-STRING_INDENT) withFont:font fontSize:fontSize lineBreakMode:UILineBreakModeMiddleTruncation baselineAdjustment:UIBaselineAdjustmentAlignBaselines]; }

58

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

29 29

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Handling Touch Events

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

59

Animating
 In iPhone applications, animation plays a very important role.  Animation is used extensively to provide the user with contextual information
and immediate feedback.

 For example, when the user navigates hierarchical data in a productivity


application, rather than just replace one screen with another, iPhone applications animate the movement of each new screen into place. The direction of movement indicates whether the user is moving up or down in the hierarchy and also provides a visual cue that there is new information to look at.

 Because of its importance, support for animation is built into the classes of
UIKit already.

60

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

30 30

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Animating

The basic steps for creating these animations are essentially the same:

 Call the beginAnimations:context: method of the view you want to animate.  Configure the animation properties.  Call the commitAnimations method of the view to begin the animation.

61

plist.file
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleDisplayName</key> <string>${PRODUCT_NAME}</string> <key>CFBundleExecutable</key> <string>${EXECUTABLE_NAME}</string> <key>CFBundleIconFile</key> <string>Icon.png</string> <key>CFBundleIdentifier</key> <string>com.yourcompany.${PRODUCT_NAME:identifier}</string>

62

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

31 31

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

plist.file
<key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1.0</string> <key>UIStatusBarHidden</key> <true/> <key>NSMainNibFile</key> <string>MainWindow</string> </dict> </plist>

63

Time to Work 5

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

32 32

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

iPhone in Action
6

Using the Accelerometers



The accelerometers in iPhone and iPod touch provide valuable input for the system and for your own custom applications. An accelerometer measures changes in velocity along a single linear axis. Both iPhone and iPod touch have three accelerometers to measure changes along each of the primary axes in three-dimensional space, allowing you to detect motion in any direction. Although you might not think measuring changes in acceleration would be very useful, in reality there is a lot you can do with the information. The force of gravity is constantly trying to pull objects to the ground. This force results in a measurable amount of acceleration toward the ground even when the device is at rest. By tracking which accelerometers are registering this acceleration, and the extent of that acceleration, you can detect the physical orientation of a device in 3D space with a fair amount of accuracy. You can then apply this orientation as input to your application. The system uses the accelerometers to monitor a device's current orientation and to notify your application when that orientation changes. If your application's interface can be displayed in both landscape and portrait mode, you should incorporate view controllers into your basic design. The UIViewController class provides the infrastructure needed to rotate your interface and adjust the position of views automatically in response to orientation changes. If you want access to the raw accelerometer data directly, you can do so using the shared UIAccelerometer object in UIKit. The UIAccelerometer object reports the current accelerometer values at a configurable interval. You can also use the data to detect the device's orientation or to detect other types of instantaneous motion, such as the user shaking the device back and forth. You can then use this information as input to a game or other application.







66

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

33 33

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Using the Accelerometers


 Accelerometer Events  Update Interval  Isolating the Gravity Component From Acceleration Data  Isolating Instantaneous Motion From Acceleration Data  Current Device Orientation
67

Example

68

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

34 34

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Accessing the User's Contacts


 The user's list of contacts is an important resource that all system applications
share. The Phone, Mail, and SMS Text applications use it to identify people the user needs to contact and to facilitate basic interactions such as starting a phone call, email, or text message. Your own applications can access this list of contacts for similar purposes or to get other information relevant to your application's needs.

 iPhone OS provides both direct access to the user's contacts and indirect access
through a set of standard picker interfaces. Using direct access, you can obtain the contact information directly from the contacts database. You might use this information in cases where you want to present contact information in a different way or filter it based on application-specific criteria. In cases where you do not need custom interface, however, iPhone OS also provides the set of standard system interfaces for picking and creating contacts. Incorporating these interfaces into your applications requires little effort but makes your application look and feel like it's part of the system.

 To access the user's contact information use the Address Book and Address Book
UI frameworks.
69

Example

70

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

35 35

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Getting the User's Current Location


 Devices that run iPhone OS are meant for users on the go.  Therefore the software you write for these devices should also take this fact
into account. And because the Internet and web make it possible to do business anywhere, being able to tailor information for the user's current location can make for a compelling user experience.

 The Core Location framework monitors signals coming from cell phone towers
and Wi-Fi hotspots and uses them to triangulate the user's current position.

 You can use this framework to grab an initial location fix only, or you can be
notified whenever the user's location changes. With this information, you can filter the information your application provides or use it in other ways.

71

Playing Audio and Video


 iPhone OS supports audio features in your application through the Core Audio and

OpenAL frameworks, and provides video playback support using the Media Player framework. sound and for parsing streamed audio. You can use it to play back simple sound effects or multichannel audio, mix sounds and position them in an audio field, and even trigger the vibrate feature of an iPhone. If you are a game developer and already have code that takes advantage of OpenAL, you can use your code in iPhone OS to position and play back audio in your games.

 Core Audio provides an advanced interface for playing, recording, and manipulating

 The Media Player framework is what you use to play back full-screen video files.

This framework supports the playback of many standard movie file formats and gives you control over the playback environment, including whether to display user controls and how to configure the aspect ratio of video content. content, while media-based applications can also use this framework to play back movie files.

 Game developers might use this framework to play cut scenes or other prerendered

72

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

36 36

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Taking Pictures with the Built-in Camera


 The Camera application on iPhone lets users take pictures and store them in a
centralized photo library, along with the other pictures they upload from their computer.

 And although the iPod touch has no camera, it does have a photo library to
hold the user's uploaded pictures. iPhone OS provides access to both of these features through the UIImagePickerController class in the UIKit framework.

 The UIImagePickerController class provides the implementation for both the


camera and photo library interfaces for your application. These are the standard system interfaces used by other applications, including the Camera and Photos applications.

 When you display the picker interface, the picker controller takes care of all of
the required user interactions and returns the resulting image to your application.

73

Time to Work 6

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

37 37

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

References
6

iPhone Dev Center

http://developer.apple.com/iphone

76

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

38 38

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

iPhone SDK: a kick start. Using Xcode 3.1 Developer Tools for iPhone OS 2.0

Instructors

Javier Gonzlez Snchez Tecnolgico de Monterrey, campus Guadalajara javiergs@itesm.mx .com/in/javiergs

Maria Elena Chvez Echeagaray Tecnolgico de Monterrey, campus Guadalajara mechavez@itesm.mx .com/in/mechavez

77

OOPSLA 2008 Tutorial OOPSLA 2008 Tutorial

39 39

Javier Gonzlez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

Worksheets

OOPSLA Tutorial OOPSLA 2008 2008 Tutorial

40 40

Javier Gonzalez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

Worksheets

OOPSLA Tutorial OOPSLA 2008 2008 Tutorial

41 41

Javier Gonzalez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

Worksheets

OOPSLA Tutorial OOPSLA 2008 2008 Tutorial

42 42

Javier Gonzalez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

Worksheets

OOPSLA Tutorial OOPSLA 2008 2008 Tutorial

43 43

Javier Gonzalez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

Worksheets

OOPSLA Tutorial OOPSLA 2008 2008 Tutorial

44 44

Javier Gonzalez & Maria Elena Chvez Gonzalez-Sanchez & Chavez-Echeagaray

You might also like