You are on page 1of 44

Creating an Application Project

iPhone

Project Templates Application Skeleton Application Bundle Using the Debugger Using the Simulator Using the Compiler Directives The Core Application Objects The Application Life Cycle The Application States and Transitions Preserving the Applications State Launching in Landscape Mode Inter-application Communication Application Preferences Application Configuration

iPhone ToolChain
XCode Objective-C, GDB

Interface Builder Graphical UI Development

Instruments Profiling, Leak Finding

Simulator Testing

Project Templates
Several project templates are provided: View-based Application. An application that uses a single view to implement its user interface. It provides a view controller to manage the view and an empty xib file to populate the view GUI elements Navigation-based Application. An application that presents data hierarchically, using multiple screens. Tab Bar Application. An application that presents a radio interface that lets the user choose from several screens. 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. OpenGL ES Application. An application that uses an OpenGL ESbased view to present images or animation. 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. Split Viewbased Application. (for iPad)

Starting a Project

(A) moves you between the project overview and the visual debugger. (B) sets your targets and configuration. These control the application you intend to build and the way you intend to build it. ( by default iPhone templates provide two configurations, Debug and Release) (C), a pop-up that offers typical project functionality like adding new files and Reveal in Finder to locate those files on your Macintosh. (D). Build and Go button ( on the device or in the simulator) (E) Info button, when clicked opens a window that you can use to customize parts of your project. (F) Groups and Files column . List includes any files used to build the application plus any other files youve added to the project. The folder system shown is completely arbitrary. Can be skipped entirely. (G) Products folder , last item in the folders list by default, contains the item you intend to build. (H) The HelloWorld.app application . Shown in red when it is not built. (I) Targets item. Click the gray disclosure triangle to reveal the application. (J) Detail lists and previews files in project. It helps find files and open them to edit. (K) pane option: Project Find (L) SCM Results , shows the status of files relative to a Source Code Management System (M) Build presents a results window for building projects, showing any errors and their details. (N) Detail pane (default selection for the project window). Lists all the files in the project. (O) offers a preview of whichever element has been selected on the top. Its also a live editor, so any changes made in the bottom pane update the file in question. (P) Resize bar sits between the top file list and the bottom editor/preview. Used to adjust the proportions between the two elements.

The Application Bundle


A bundle is a directory in the file system that groups related resources together in one place. An iOS application bundle contains:
the application executable file and supporting resource files such as: application icons, image files, and localized content.

Linked Frameworks Graphics, sound, bluetooth, etc

The Executable

Resources Images, sounds, data, IB files Monday, January

Boilerplate Code

Your Apps Code These folders, called groups are just abstractions to help you organize your project -- they dont even exist in the filesystem. Rearrange however you want.

Application Skeleton
Main.m
Creates a primary autorelease pool Invokes the application Event loop
int retVal = UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString*delegateClassName );

appDelegate(.h/.m)
Responsible for initializing a windowing system at launch time and wrap up at termination Key player for handling memory warnings Monitor the high-level behavior of the application

viewController (.h/.m/.xib)

UI-Driven Programming

Nearly everything in your entire project is essentially just a callback. main.m

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

This is the entire main routine!

UI-Driven Programming

So where is your hook to implement code?

- (void)applicationDidFinishLaunching:(UIApplication *)application { // Override point for customization after app launch ! [window makeKeyAndVisible]; }

... the applicationDidFinishLaunching callback

UI-Driven Programming UIApplication ------- UIAppDelegate - (void)applicationDidFinishLaunching:(UIApplication *)application { //Initialize the User Interface [window makeKeyAndVisible]; } After which point your app is almost entirely UI Driven

The Interface Builder window for a view controller .xib

View : The view is by default a member of the UIView class Files Owner represents the view controller. An abstract class, and it is a proxy because it plays a role in IB, but the object is not itself embedded in the .xib archive. View controllers dont have a visual presentation. They manage views, but they dont display anything of their own. Each view controller has an instance variable called view which is set to some UIView (in this case, the one at the right) that is responsible for providing the actual onscreen presentation. In the case of view controllers, the Files Owner proxy represents the object that loads and owns the .xib. First Responder: a proxy object. It represents the onscreen object that is currently responding to user touches.
It changes during the lifetime of an application as users interact with the screen.

Outlets
Instance variables ( in the IB-talk).

Using the Debugger

The Debug View

The Debug View

Using the Simulator


Rotating the device Hardware > Rotate Left (Command-left arrow) and Hardware > Rotate Right (Command-right arrow). Shaking the device Hardware > Shake Gesture (Command-Control-Z). Pressing the Home Key
Click the Home button on the Simulator screen or choose Hardware > Home (Command-Shift-H). Hardware > Lock (Command-L). Click with the mouse, either a single- or double-click. Click the virtual keyboard or type on the Mac keyboard. Click, drag, and release with the mouse. The speed of the drag determines the action. For flicks, drag very quickly. Press and hold the Option key on your keyboard. When the two dots appear, drag them toward each other or away from each other. Hardware > Simulate Memory Warning.

Locking the device


Tapping and double-tapping

Tapping on the keyboard


Dragging, swiping, and flicking Pinching in or out Running out of memory

In-progress phone call (visual display only)


Hardware > Toggle In-Call Status Bar. On the iPhone, you can run an application while on a phone call. The in-call bar appears at the top of the screen for the duration of the call

Misc.
The style of the project window depends on an Xcode setting. Choose Xcode > Preferences (Command-,),
select the General pane, and choose the layout from the pop-up: All-In-One layout: combines operations to a single window Condensed: separate windows for most tasks Default: has a core project window and separate tool windows.

The simulator versions of the frameworks are located in the Xcode developer directory:
/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0.sdk/System/Library

nib2obj hosted at http://github.com/akosma/nib2objc/tree/master


Converts Interface Builder Files to Their Objective-C Equivalents

Enabling Zombies:
a zombie is an object that has been destroyed or released that you are still trying to send messages to. debug mode lets you gather information about messages sent to invalid objects Add the NSZombieEnabled to the variables section of the Executable Info

Using Compiler Directives


target defines: TARGET_IPHONE_SIMULATOR and TARGET_OS_IPHONE.
if TARGET_IPHONE_SIMULATOR Code specific to simulator #else Code specific to iPhone #endif

Include code specific to a certain version


#ifdef _USE_OS_3_OR_LATER #import <MapKit/MapKit.h> #endif

checking the minimum OS version required to run the application.


#if __IPHONE_OS_VERSION_MIN_REQUIRED < 30000
Pre-3.0 Code

#else
3.0 Code #endif

#define __IPHONE_2_0 20000 , #define __IPHONE_2_1 20100 #define __IPHONE_2_2 20200 , #define __IPHONE_3_0 30000

Pragma marks: organize source code by adding bookmarks into the method list pop-up button at the top of each Xcode window.
#pragma mark delegate functions #pragma mark - ( spacer )

Building for distribution


App Store : Must be signed by a valid distribution provision profile using an active developer identity. Ad Hoc Distribution (send the applications to up to 100 registered devices )


/* * main.m * <<PROJECTNAME>> * * Created by <<FULLUSERNAME>> on <<DATE>>. * Copyright (c) <<YEAR>> <<ORGANIZATIONNAME>>. All rights reserved. * */ Your user and organization names are retrieved from your Address Book

These settings can be overwritten by a command line.


defaults write com.apple.Xcode PBXCustomTemplateMacroDefinitions '{ORGANIZATIONNAME = "Apple, Inc." ; FULLUSERNAME = Mike J.}'

Using Instruments
Instruments plays an important role in tuning applications. offer a suite of tools to monitor performance. Leak detection: track, identify, and resolve memory leaks within the program. Cached Objects Allocation Monitoring / Simulate Memory Warnings:
Hardware > Simulate Memory Warning sends calls to the application delegate and view controllers, asking them to release unneeded memory Allows creation of trace files to compare runs.

Using the Clang Static Analyzer


helps detect bugs in Objective-C programs. Creates bug reports for source code and displays them in an Xcode feedback window. Can be download from http://clang-analyzer.llvm.org/.

The Core Application Objects

The Application Life Cycle

Applications States and Transitions


Not running The application has not been launched or was running but was terminated by the system. Inactive Running in the foreground but not receiving events. (ex: when the user locks the screen or the system prompts the user to respond to some event) Active Running in the foreground and is receiving events. Background In the background and executing code. Available only in iOS 4 and later and on devices that support multitasking. Suspended In the background but is not executing code. The suspended state is available only in iOS 4 and later. otherwise terminated and moved to the not running state.

Methods of your application delegate called during state transitions: application:didFinishLaunchingWithOptions:


launchOptions: A dictionary indicating the reason the application was launched (if any). The contents of this dictionary may be empty in situations where the user launched the application directly. Called during the initial startup sequence followed by either the

applicationDidBecomeActive: or applicationDidEnterBackground:
NSApplicationDidFinishLaunchingNotification can be added in any class to listen to the same event

applicationDidBecomeActive: applicationWillResignActive:
Called when the user presses the Home button or the system launches another application

applicationWillEnterForeground:

The application is about to enter the foreground. UIApplicationWillEnterForegroundNotification notification is also available for tracking when your application reenters the foreground.

applicationWillTerminate:
The application is about to be terminated and purged from memory entirely. Use this method to perform any final clean-up tasks, such as freeing shared resources, saving user data, invalidating timers, and storing enough application state to reconstitute the applications interface when it is relaunched.

applicationDidEnterBackground:

Moving to the Background


At least two things should be always done in the applicationDidEnterBackground: method: Prepare your application to have its picture taken. When the applicationDidEnterBackground: method returns, the system takes a picture of the applications user interface and uses the resulting image for transition animations. If any views in the interface contain sensitive information, you should hide or modify those views before the applicationDidEnterBackground: method returns. Save user data and application state information. All unsaved changes should be written to disk when entering the background. The application might be quietly terminated while in the background for any number of reasons. This operation can be performed from a background thread as needed. applicationDidEnterBackground: method has approximately five seconds to finish any tasks and return. If the method does not return before time runs out, the application is terminated and purged from memory. If more time is needed to perform tasks, call the beginBackgroundTaskWithExpirationHandler: method to request background execution time and then start any long-running tasks in a secondary thread. Regardless of whether you start any background tasks, the applicationDidEnterBackground: method must still exit within five seconds.

Application Termination
Applications are generally moved to the background and suspended if any of the following conditions are true, the application is terminated and purged from memory instead of being moved to the background: The application is linked against a version of iOS earlier than 4.0. The application is deployed on a device running a version of iOS earlier than 4.0. The current device does not support multitasking; The application includes the UIApplicationExitsOnSuspend key in its Info.plist file

Preserving the Applications State


At a minimum, save:
The currently visible view controller The structural arrangement of the view controllers Information about each view controller, including: The class name of the view controller, which is used to recreate the view controller during the next launch cycle References to the data being managed by the view controller

One approach is to build a property list that is structured to match the organization of the view controllers. The property list saves information about each view controller in a dictionary object. The keys of the dictionary identify properties of the view controller Should save information only about those view controllers that are not part of your applications default user interface. Save in applicationDidEnterBackground: or applicationWillTerminate: as an application preference. In application:didFinishLaunchingWithOptions: method, load the property list from preferences

Launching in Landscape Mode


Perform the following tasks to make it appear to launch in landscape mode initially: Add the UIInterfaceOrientation key to the applications Info.plist file and set the value of this key to either UIInterfaceOrientationLandscapeLeft or UIInterfaceOrientationLandscapeRight. Lay out the views in landscape mode and make sure that their autoresizing options are set correctly. Override the view controllers shouldAutorotateToInterfaceOrientation: method and return YES only for the left or right landscape orientation and NO for portrait orientations.

To track whether data protection is currently enabled. The application delegate can implement the applicationProtectedDataWillBecomeUnavailable: and applicationProtectedDataDidBecomeAvailable: methods and use them to track changes to the availability of protected data. An application can register for the UIApplicationProtectedDataWillBecomeUnavailable and UIApplicationProtectedDataDidBecomeAvailable notifications. The protectedDataAvailable property of the shared UIApplication object indicates whether protected files are currently accessible.

Communicating with Other Applications


Use URL schemes to initiate specific requests Built-in support for: http, mailto, tel, and sms URL schemes. Supports httpbased URLs targeted at the Maps, YouTube, and iPod applications. The handlers for these schemes are fixed and cannot be changed. the Apple-provided applications are launched first in case it is identical to user scheme Create an NSURL object with some properly formatted content pass that object to the openURL: method of the shared UIApplication object. The openURL: method launches the application that registered to receive URLs of that type and passes it the URL. At that point, control passes to the new application.
Example:
NSURL *myURL = [NSURL URLWithString:@"todolist://www.acme.com?Quarterly%20Report#200806231300"]; [[UIApplication sharedApplication] openURL:myURL];

To register custom URL Scheme, include the CFBundleURLTypes key in your applications Info.plist file

Displaying Application Preferences


Preferences that the user might change frequently should be presented from inside the application using a custom interface. Preferences that are not likely to change frequently should be handled using a Settings bundle. A settings bundle is a custom resource that you create using Xcode. A settings bundle contains a specification for how the Settings application should display the preferences. Specifically, it indicates what controls and labels should be displayed and how values entered by the user should be saved to the preferences database. Settings bundles can also contain custom images for controls that support them. access preferences using the NSUserDefaults or CFPreferences APIs.

Disable Screen Locking


To disable screen locking, set the idleTimerDisabled property of the shared UIApplication object to YES. Reset this property to NO at times when the application does not need to prevent screen locking. NextPrevious

Application Configuration
Set up the applications properties to customize its runtime environment Configure its entitlements to take advantage of iOS security features Xcode uses two main types of property-list file to store runtime-configuration information for the application: Information-property list: (info-plist files) contain essential information used by the application and iOS. Entitlements: define properties that provide the application access to iOS features (such as push notifications) and secure data (such as the users keychain).

Application Entitlements

Building for iPhone


To create applications that run on actual devices, there are three ways
building for development
To test locally on the device

building for distribution


To build for AppStore

building for ad hoc distribution.


To build for up to 100 registered devices

You might also like