iphone App Basics iphone and ipod touch Development Fall 2009 Lecture 5
Questions?
Announcements Assignment #1 due this evening by 11:59pm Remember, if you wish to use a free late you must email me before midnight Assignment #2 out this evening Due Tuesday September 22 nd by 11:59pm
Today s Topics iphone OS Stack Anatomy of an iphone App Running an iphone App Interface Builder Adding UI Elements Outlets & Actions
iphone OS Stack
iphone OS Stack Core OS OS X kernel UNIX services Hardware drivers Power management Management of Threads File system Your App Cocoa Touch Media Core Services Core OS Network IPC
iphone OS Stack Core Services Bonjour Sockets URL utilities Address Book Core Location SQLite Collections Your App Cocoa Touch Media Core Services Core OS File Access Core Data
iphone OS Stack Media Core Audio Core Graphics OpenGL ES Quartz Core Media Player Audio Services Images Your App Cocoa Touch Media Core Services Core OS
iphone OS Stack Media UIKit Address Book UI Game Kit Map Kit Message UI Touch/Multi-touch Accelerometer Your App Cocoa Touch Media Core Services Core OS
Cocoa Touch Decomposition Cocoa Touch UIKit User interface elements Application runtime Event handling Hardware APIs Foundation Utility classes Collection classes Object wrappers for system services Subset of Foundation in Cocoa
iphone OS Stack Your App Xcode templates Your code leveraging lower level APIs Your App Cocoa Touch Media Core Services Core OS
Anatomy of an iphone App
Choosing an iphone App Template Fire up Xcode and select File New Project... Several templates to select from as a starting point We ll start with what is probably the easiest iphone template the view-based application Select View-based Application, then click Choose... Name the project HelloWorld and Save
New View-Based Application
Stubbed Out Project Once you name and save your project, you ll notice that Xcode created a lot for you as part of this template
Classes Classes typically consist of ObjC code that we can tailor to meet the needs of our application Additionally, when we add classes to our project, they are usually placed under Classes as well For this app template we see that Xcode has automatically created two classes for us
Classes ProjectNameAppDelegate.[mh] The AppDelegate class handles life-cycle events for our application, such as... App startup App shutdown
Classes ProjectNameViewController.[mh] The default ViewController class is responsible for managing what appears on the screen
Other Sources Source files that are automatically generated by Xcode Typically, you will not need to do anything with these files Usually 3 rd party libraries are placed here as well
Other Sources ProjectName_Prefix.pch The.pch file is a pre-compiled header file that is created by Xcode to improve performance of processing headers in main
Other Sources main.m The main.m file is responsible for actually launching your application
Resources The resources folder contains no source code, but the files here are vital to your application App icon App name GUIs Other files you might add here include Images Audio
Resources ProjectNameViewController.xib The HelloWorldViewController contains the UI that we ll initially see when the app loads You can think of the.xib file as containing a freeze dried version of our UI elements
Resources MainWindow.xib The Main Window is typically responsible for loading the first view when the app loads Usually this displays one of the other.xib files
Resources ProjectName-Info.plist The Info.plist file contains basic app information such as App icon App name Name of the main.xib file
Frameworks Lists the various libraries that our app is dependent upon
Frameworks UIKit UIKit provides the fundamental objects for constructing and managing your application's user interface Events Windows Views Controls Multi-touch
Frameworks Foundation UIKit provides the foundation for Cocoa development NSObject Basic data types Collections OS Services
Frameworks CoreGraphics Provides a C-based API that is a low-level, lightweight 2D rendering engine Path based drawing Gradients Images Transforms PDF
Products Contains the files that will be created by the build process
Products ProjectName.app The actual iphone application
Running an iphone App
Deployment Options Two options for building and deploying your iphone apps... On device Build for ARM iphone architecture Requires code signing certificate Push to device to run and test On simulator Build for x86 Mac architecture, runs in a simulator No code signing required Run and test on Mac
iphone Simulator The simulator is sufficient for the apps that we re going to be building to start out with However, there are some limitations in the simulator No camera No accelerometers Limited multi-touch GPS fixed at Apple headquarters Etc...
iphone Simulator Location The simulator is located under Macintosh HD Developer Platforms iphonesimulator.platform Developer Applications iphone Simulator.app I d recommend that you either launch it as needed from Xcode, through Spotlight, or add it to the dock
Targeting the Simulator
Building and Running To test the app from the Build menu select Build and Run Or, simply type R This will... Build your app Install it into the simulator Automatically launch it
App Running in Simulator
Congratulations You ve successfully completed the most basic Hello World of iphone apps......a flashlight app : )
Interface Builder
NIB files Earlier we stated that.xib files contained a freeze dried representation of our GUI The files are XML-based and named with a.xib extension (used to be.nib) So, for historical reasons they are still called NIBs NIB files are manipulated in another part of the SDK called Interface Builder
Interface Builder Interface Builder (or IB for short) is where we edit our NIBs IB contains: A canvas on which we create our GUI A library of widgets Tools to tweak the appearance of the UI
Interface Builder Location IB is located at Macintosh HD Developer Applications Interface Builder.app I d recommend that you either launch it as needed from Xcode, through Spotlight, or add it to the dock
Multi-Window Display
Main NIB Window The main NIB window contains some objects which are used for a variety of purposes We ll talk about these objects in more detail later
View Window The view window is our app s canvas This is where we ll build out the UI If not visible, double clicking the View icon in the NIB window should open it
Inspector The Inspector is a 4 tabbed panel that lists details for the currently selected UI element Attributes Connections Size Identity If not visible, select Tools Inspector, or I You can also jump between the various tabs using 1, 2, 3 & 4
Library The library contains our palette of UI elements from which to choose Has a handy search bar at the bottom to filter the list If not visible, select Tools Library, or L
Adding UI Elements
Hello iphone World! Let s use Interface Builder to add some text to our view We ll customize some of the defaults to build a (slightly) more interesting screen Font sizes Font colors Font family Text alignment Background colors
Drag and Drop Simply click, then drag and......drop here
Change Text To change the default text of most UI elements, you simply double click and enter the new label...
Guide Lines You ll notice handles around the edges of UI elements, IB allows you to resize by simply dragging and even offers various guides that will appear to help align your widgets
Inspector Attribute Tab We use the attributes tab of the Inspector to customize the visual aspects of our UI elements The specific attributes you can tweak will change based on the current UI element selected
Testing our Changes Save the NIB file using File Save, or S Then return to Xcode and re-run the app IB will automatically redeploy the changes to the simulator
Hello iphone World!
Outlets & Actions
Building a More Interesting App We ve seen that Interface Builder is a powerful tool that allows us to build out pretty nice looking GUIs and allows us to customize the appearance of our app However, that only gets us so far... What about user interaction?
A More Interesting Hello World App
UI Elements
Steps to Build Our App Construct the view this is simply drag and drop like the previous Hello iphone World app Need a way to get a handle on UI elements to be able to read and write their values Read from text field Write to the label Need a way to wire up the button to respond to events When the button is pressed display the message
IBOutlet When we click the button, we need retrieve the name from the text field and set the text on the label accordingly We need a mechanism to associate UI elements in the NIB to variables in our code A reference from code to a UI element in a NIB is called an outlet and is declared by the keyword IBOutlet
IBOutlets in HelloNameViewController.h #import <UIKit/UIKit.h> @interface HelloNameViewController : UIViewController {! UILabel *label;! UITextField *field;! } @property(nonatomic,retain) IBOutlet UILabel *label; @property(nonatomic,retain) IBOutlet UITextField *field; @end Typically UI elements are declared nonatomic and retain Declared outlet
IBOutlets in HelloNameViewController.m #import "HelloNameViewController.h" @implementation HelloNameViewController @synthesize field; @synthesize label; Remember to synthesize properties /*... bunch 'o commented out auto-generated methods... */ - (void)didreceivememorywarning { [super didreceivememorywarning]; } - (void)viewdidunload { } - (void)dealloc { self.label = nil; self.field = nil; [super dealloc]; } @end Also need to cause properties to get released when done
IBOutlet Currently, these are just declarations that the variables are capable of referencing a UI element Hey you, we have some outlets here!
IBOutlet We need to actually perform the linkage to associate the outlet with a particular instance of a UI element in IB IBOutlet (It is a common error to miss this step when getting started)
Wiring Up the IBOutlet for the Text Field Control click, drag and......drop here
Wiring Up the IBOutlet for the Text Field Select the outlet for this UI element
Wiring Up the IBOutlet for the Label Control click, drag and......drop here
Wiring Up the IBOutlet for the Label Select the outlet for this UI element
Verifying Outlet Connections You can verify that the connections were created by selecting File s Owner from the NIB file window and view the connections tab...
IBAction When we click the button, we need execute some code to read the value of one UI element and set another We need a mechanism to associate interaction with a UI element (a button press) in the NIB to a method in our code A method that is capable of handling events is said to respond to actions and is identified by the keyword IBAction
IBActions in HelloNameViewController.h #import <UIKit/UIKit.h> @interface HelloNameViewController : UIViewController {! UILabel *label;! UITextField *field;! } - (IBAction)sayHello; Declared action method @property(nonatomic,retain) IBOutlet UILabel *label; @property(nonatomic,retain) IBOutlet UITextField *field; @end
IBActions in HelloNameViewController.m #import "HelloNameViewController.h" @implementation HelloNameViewController @synthesize field; @synthesize label; - (IBAction)sayHello { /*... OUR CODE HERE... */ } /*... bunch 'o commented out auto-generated methods... */ /*... didreceivememorywarning and viewdidunload methods... */ - (void)dealloc {! self.label = nil;! self.field = nil; [super dealloc]; } @end
How to Use UILabel & UITextField? Where can we find out how to read the value of a UITextField and write the value for a UILabel?
IBActions in HelloNameViewController.m #import "HelloNameViewController.h" @implementation HelloNameViewController @synthesize field; @synthesize label; - (IBAction)sayHello {! self.label.text = [NSString stringwithformat:@"hello, %@", self.field.text]; } /*... bunch 'o commented out auto-generated methods... */ /*... didreceivememorywarning and viewdidunload methods... */ - (void)dealloc {! self.label = nil;! self.field = nil; [super dealloc]; } @end
IBAction Currently, these are just declarations that these methods are capable of performing actions Hey you, we have some actions here!
IBAction We need to actually perform the linkage to associate an event in the UI with an action method in the code IBAction (It is a common error to miss this step when getting started)
Wiring Up the IBAction for the Button Control click, drag and......drop here
Wiring Up the IBAction for the Button Select the action for pressing this button
Verifying Action Connections We can again verify that our connections were correctly wired up using the connections inspector tab However, this time we need to click on the UI element that we setup to perform the action Bunch of events that we can bind to Button presses are typically bound to the Touch Up Inside event
When to Declare IBOutlet and IBAction As a general rule, you only need to declare an IBOutlet if you need to read or write any of that UI elements attributes For example, we didn t declare the button to be an IBOutlet because we didn t change the button at runtime Declare an IBAction for methods you plan to call from a UI element If you re not calling it from a UI element, there s no real need to declare it as an IBAction
Running Our App Save changes in IB and Xcode, then run the app Again, the app will automatically be deployed and run in the simulator
Notice Anything Wrong? Return doesn t do anything!
Behind the Magic Next class we ll dive a bit deeper into what we saw happening magically this evening What is the File s Owner? What is the First Responder? How does a NIB get executed? What are all these commented out methods? How does all of this get executed? How do I make the keyboard disappear when the user presses the return key? We ll also look at some of the design patterns that are present in our application
Additional Resources The iphone OS Technology Overview does a thorough job of discussing the various iphone OS layers http://developer.apple.com/iphone/library/documentation/ Miscellaneous/Conceptual/iPhoneOSTechOverview/ iphone Application Programming Guide http://developer.apple.com/iphone/library/documentation/ iphone/conceptual/iphoneosprogrammingguide/
For Next Class Read chapter 1 of the iphone Application Programming Guide up to (including) the section title Handling Critical Application Tasks http://developer.apple.com/iphone/library/documentation/ iphone/conceptual/iphoneosprogrammingguide/