About Objects Introduction to iPhone Programming SECTION 2 Developer–oriented training. www.About Objects .com Friday, October 9, 2009
About Objects
Introduction to iPhone ProgrammingSECTION 2
Developer–oriented training.
www.AboutObjects.com
Friday, October 9, 2009
Overview
Friday, October 9, 2009
What is iPhone SDK?
Layered libraries and frameworks
Development tools
Documentation
Friday, October 9, 2009
Mobile Platform
Resource constrained environment
Memory
CPU
Graphics
Battery
Smaller API footprint
Requires extra attention to details like memory management, etc.
Friday, October 9, 2009
iPhone SDK
Media
Core OS
Cocoa Touch
Core Services
Friday, October 9, 2009
Core Services
6
Core Foundation C Library Strings, dates, collections, threads, etc.
Address Book Framework Managing contact info
CFNetwork C Library Low-level network access
Core Location Framework Accessing geospatial positioning info
Security Framework Manages certificates, public/private keys, etc.
SQLite C Library Accessing lightweight SQL database
XML Support ObjC Class NSXMLParser class
Friday, October 9, 2009
Media
iPhone SDK
Core OS
Cocoa Touch
Core Services
Friday, October 9, 2009
Media
Open GL ES
Core Graphics
Core Animation
Core Audio
Friday, October 9, 2009
iPhone SDK
Cocoa Touch
Media
Core OS
Core Services
Friday, October 9, 2009
Cocoa Touch
UIKit
Foundation Framework
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Foundation Framework
Wrappers for strings, numbers, dates, binary data
Collection classes (arrays, sets, dictionaries, etc.)
Bundles (dynamically loadable app modules)
User preferences
Threads and run loops
Files, streams and URLs
Bonjour (dynamic discovery)
11
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
UIKit
Application management and integration (via URL schemes)
Graphics and windowing
Handling touch events
User interface views and controls
Text handling
Web content
Device-specific features (accelerometer, camera, photo library)
12
Friday, October 9, 2009
XCode
IDE for iPhone Projects
Build
Run (Simulator, device)
Debug
Source code management (SCM)
Documentation
Friday, October 9, 2009
Interface Builder
GUI design tool
Doesn't generate code
Works with ‘Freeze-dried’ objects
Archived in .nib files
Dynamically loaded
Objects deserialized at load time
Friday, October 9, 2009
IB Learning Approach
Start coding using mostly APIs
Migrate to IB when we have solid grounding at the API level
Friday, October 9, 2009
Xcode
Friday, October 9, 2009
Xcode
Xcode IDE and Interface Builder (IB)
Located in /Developer/Applications
Drag icons to dock to keep them handy
To create a new project
1. Select File > New Project... from the menu
2. Select iPhone OS | Application in left pane
3. Choose Window-Based Application project template
4. Save as HelloWorld
Friday, October 9, 2009
Configuring XcodeAll-In-One Layout
Temporarily close project
Go to Xcode > Preferences
General pane
Select All-In-One from Layout dropdown
Building and Running
Debugging pane
Select Show Console & Debugger from On Start dropdown
Friday, October 9, 2009
Xcode Groups & Files
Groups are logical groupings of files
Don't map to folder structure
By default all sources in top-level directory
You can manually map individual groups to subfolders
File references are also logical
Add/Delete = add/delete files from build
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
main.m
main() function
Defined in main.m
UIApplicationMain()UIApplication singleton
Starts program's main event loop
20
int main(int argc, char *argv[]){ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; int val = UIApplicationMain(argc, argv, nil, nil); [pool release]; return val;}
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
MainWindow.xibInterface Builder file in XML format
Compiled into .nib (NeXT Interface Builder) file
21
<?xml version="1.0" encoding="UTF-8"?><archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="7.02"> <data> ... <object class="NSMutableArray" key="IBDocument.RootObjects" id="1000"> <bool key="EncodedWithXMLCoder">YES</bool> <object class="IBProxyObject" id="372490531"> <string key="IBProxiedObjectIdentifier">IBFilesOwner</string> </object> ... <object class="IBUITableView" id="685065310"> <nil key="NSNextResponder"/> <int key="NSvFlags">274</int> <string key="NSFrameSize">{320, 480}</string> <bool key="IBUIOpaque">NO</bool> ... </object> </object>
Friday, October 9, 2009
info.plist
Config info for UIApplicationMain()App id (namespace for app)
Name displayed in UI
App icon
App version
Name of main nib file
Name of principal class (allows you to subclass UIApplication)
<key>CFBundleIdentifier</key><string>com.aboutobjects.lab.*</string>
<key>CFBundleDisplayName</key><string>My App</string>
<key>CFBundleIconFile</key><string>myicon.png</string>
<key>CFBundleVersion</key><string>1.17</string>
<key>NSMainNibFile</key><string>MainWindow.xib</string>
<key>NSPrincipalClass</key><string>UIApplication</string>
Friday, October 9, 2009
Plist Editor
Plus icon for new rows
Drop down for keys
To view as XML
Right-click in Groups and Files
Select Open As... > Source Code File
To switch back
Right-click in Groups and Files
Open As... > XML Property List
Friday, October 9, 2009
Document Browser
API docs
Guides
Browse Mode
Bookmarks
Friday, October 9, 2009
First Application
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Programmatic vs. IB
To create a Nibless project:
1. Remove MainWindow.xib
2. Delete nib file name in info.plist
3. Pass name of app delegate to UIApplicationMain in main.m
4. Create the app's main window in your app delegate class
26
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
UIApplication Class
Obtaining an instance
+ sharedApplication
Properties
window
keyWindow
delegate
StatusBar Orientation and Style
- setStatusBarOrientation:animated:
- setStatusBarStyle:animated:
- setStatusBarHidden:animated:
27
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
The main() Routine
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal;}
28
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
What is a Delegate?
Common design pattern in Cocoa and Cocoa Touch.
Lets you customize behavior of framework classes without subclassing.
Certain key framework classes (such as UIApplication, UITableView, etc.) declare a property named delegate.
You can set this property to point to an instance of any class that implements one or more methods of corresponding delegate protocol
Instance then becomes target for these run-time messages
Your implementation of these methods can do whatever you like
29
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Application Delegate
Implements UIApplicationDelegate Protocol
All methods optional
UIApplication calls delegate methods to notify of significant application-wide events
App launch and termination
Memory warnings
Changes in orientation
Becoming the active application and being deactivated
Also provides implementation for opening URLs
30
Friday, October 9, 2009
Startup Sequence
instantiate
instantiate
setDelegate:
run
applicationDidFinishLaunching:
UIApplicationMain
(C function) UIApplication AppDelegate
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Registering Your App Delegate
App delegate can be (and often is) registered in the .nib file
To register programmatically:
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, @"MyAppDelegate"); [pool release]; return retVal;}
32
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Implementing Delegate Methods
did... and will... delegate methods simply notify delegate of events
should... methods allow delegate to alter behavior
33
- (void)applicationDidFinishLaunching:(UIApplication *)application{ CGRect frameRect = [[UIScreen mainScreen] bounds]; UIWindow *myWindow = [[UIWindow alloc] initWithFrame:frameRect]; [self setWindow:myWindow]; [myWindow release]; ...}
- (void)applicationWillTerminate:(UIApplication *)application{ // Persist application state ...}
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
UIView
Subclass of UIResponder
UIResponder defines behavior for classes that can respond to events
View Hierarchy
UIView defines subviews property (NSArray)
Methods to manage drawing, hit testing, etc.
Responsibilities
Drawing
Animation
Responding to events (touches, etc.)
34
Friday, October 9, 2009
View Hierarchy
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
UIView Behavior
Defines rectangular area for drawing
Implements drawing behavior
Maintains list of subviews
Tracks whether needs redisplay
Converts coordinates
Manages scrolling
Manages layers
Provides animation
36
Properties Methods
backgroundColor initWithFrame:
opaque addSubview
frame drawRect:
bounds exchangeSubviewAtIndex:
center hitTest:withEvent:
hidden insertSubview:atIndex:
subviews layoutIfNeeded
superview sendSubviewToBack:
tag setNeedsDisplay
layer setNeedsDisplayInRect:
transform sizeToFit
userInteractionEnabled viewWithTag:
autoresizesSubviews removeFromSuperview:
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
View Geometry
UIView class
Defines a rectangular drawing area
Provides built-in drawing behavior
Each view maintains its own local coordinates
Frame and Bounds rectangle
Frame is a computed value based on bounds and center properties
Coordinates 0,0 are at upper left corner of view
37
Friday, October 9, 2009
Core Graphics Types
CGFloat
C typedef conditionally compiled as float on 32-bit platforms, double on 64-bit
CGPoint
x, y coordinates of origin of a view or graphic element
CGSize
width and height (both CGFloat)
CGRect
origin (CGPoint) and size (CGSize)
// From CGGeometry.h
/* Points. */struct CGPoint { CGFloat x; CGFloat y;};typedef struct CGPoint CGPoint;
/* Sizes. */struct CGSize { CGFloat width; CGFloat height;};typedef struct CGSize CGSize;
/* Rectangles. */struct CGRect { CGPoint origin; CGSize size;};typedef struct CGRect CGRect;
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
CG Convenience Functions
CGPointMake(CGFloat x, CGFloat y)
Returns CGPoint initialized with provided values
CGPoint myPoint = CGPointMake(0.0, 0.0);
CGSizeMake(CGFloat width, CGFloat height)
Returns CGSize initialized with provided values
CGSize mySize = CGSizeMake(120.0, 240.0);
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
Returns CGRect initialized with provided values
CGRect myRect = CGRectMake(0.0, 0.0, 120.0, 240.0);
39
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
UIWindow
Subclass of UIView
Root of the view hierarchy
Acts as bridge to UIApplication
UIApplication distributes events from the event queue and connects views to the window server
Dispatches events to its subviews
Manages key status
Converts coordinates
40
windowLevel
keyWindow
makeKeyAndVisible
becomeKeyWindow
makeKeyWindow
resignKeyWindow
convertPoint:toWindow:
convertPoint:fromWindow:
convertRect:toWindow:
convertRect:fromWindow:
sendEvent:
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Creating a Window
Use UIScreen to compute initial frame rectangle
+mainScreen class method returns singleton instance
+ (UIScreen *)mainScreen
-bounds method returns main screen's bounds rectangle
-applicationFrame method returns bounds minus the status bar area
Use initWithFrame: method (inherited from UIView) to init window
Designated initializer for UIView and its subclasses
- (id)initWithFrame:(CGRect)frameRect;
41
CGRect frameRectangle = [[UIScreen mainScreen] applicationFrame];UIWindow *myWindow = [[UIWindow alloc] initWithFrame:frameRectangle];
Friday, October 9, 2009
First App: Hello World!
Create Window-Based App Project
Delete .xib file in the Resources group
Delete the .nib file name in info.plist
Create MyAppDelegate Class
Delete .h and .m files in Classes group
Right-click Classes and select Add > New File...
Select iPhone OS | Cocoa Touch Classes in left pane and choose NSObject subclass
Save as MyAppDelegate
Edit main.m
Replace last argument in UIApplicationMain with @"MyAppDelegate"
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Declaring the Delegate
MyAppDelegate.h
Adopt the UIApplicationDelegate protocol
Add window property to contain your application's UIWindow instance
43
@interface MyAppDelegate : NSObject <UIApplicationDelegate>{ UIWindow *_window;}
// accessor methods
- (UIWindow *)window;- (void)setWindow:(UIWindow *)window;
@end
protocol declaration
Friday, October 9, 2009
- (void)applicationDidFinishLaunching:(UIApplication *)application{ // UIScreen represents the entire screen. Its applicationFrame method // returns the rectangle that corresponds to the entire screen minus // the status bar. CGRect is a C struct containing four floating // point values that represent the x and y coordinates of the upper left // corner, plus width and height. CGRect windowRect = [[UIScreen mainScreen] applicationFrame]; UIWindow *window = [[UIWindow alloc] initWithFrame:windowRect]; [window setBackgroundColor:[UIColor lightGrayColor]]; [self setWindow:window]; // Create an empty view with a different background color so we can // see something on the screen. The four float constants define the // x, y, width, and height of the view's frame rectangle. CGRect viewRect = { 20.0, 100.0, 280.0, 200.0 }; UIView *myView = [[UIView alloc] initWithFrame:viewRect]; [myView setBackgroundColor:[UIColor darkGrayColor]]; // If we don't make the view a subview of our window, it won't be drawn // on the screen. [window addSubview:myView]; // Windows are hidden by default, so make the window visible. 'Key' here // means that the window is capable of receiving key presses from the // keyboard -- though we're not taking advantage of that yet. [window makeKeyAndVisible]; // The calls to +alloc earlier in this method are paired with calls // to release. The -setWindow: message calls -retain, so the window // will not be deallocated until later, when -dealloc is called. Similarly, // -addSubview: indirectly calls -retain, so no worries there either. [window release]; [myView release];}
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Implementing the Delegate1. Implement -applicationDidFinishLaunching: delegate method
1.1. Get the application frame rectangle from UIScreen
1.2. Use it to create a UIWindow instance
1.3. Set its background color to [UIColor lightGrayColor]
1.4. Store the instance in the window instance variable
1.5. Create an instance of UIView smaller than the window
1.6. Set its background color to a darker gray ([UIColor darkGrayColor])
1.7. Add the view to the window's subviews
1.8. Tell the window to make itself visible and make itself the key window
1.9. Balance calls to +alloc with calls to -release
2. Implement accessor pair (or synthesize property) for window ivar
3. Implement -dealloc to release window
45
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
App Configuration
Some useful keys in Info.plist:
46
CFBundleDisplayName Name displayed below your app's icon
NSMainNibFile Name of the app's nib file (without the .nib extension)
UIStatusBarStyle Initial status bar style. Default is UIBarStyleDefault
UIStatusBarHidden If set to true, hides the status bar on startup
UIInterfaceOrientation Determines whether app launches in landscape or portrait mode
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Keyboard Shortcuts
47
Action Keys Comment
Build ⌘B Build the app without running; allows you to check for build errors and warnings before trying to run the app
Run ⌘R Build if necessary and run (in Simulator by default; to change target device, use drop-down in upper left corner of Xcode)
Debug ⌥⌘Y Option-Command-Y
Edit ⌘0 Command-zero
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Lab Exercise
Get your application running!
If it's working, the application will have a light gray background with a darker gray rectangle on it when the app starts up
Once it's working, we can add some more interesting stuff
48
Friday, October 9, 2009
Programming Considerations
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Frameworks
Foundation
Scaled-down version of desktop Foundation framework
UIKit
Draws on overall design of AppKit framework
Many classes are similar
Implements similar mechanisms
Target/Action
View Hierarchy
Responder Chain
50
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
App StylesProductivity
Hierarchical model to present/manipulate information
Navigation and other controls
Utility
Widget style patterns
Flip for preferences
Immersive
Media players, games, etc. that take over full screen
Use HUD controls for transport control, etc.
51
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Performance Considerations
Constraints of iPhone platform
One app at a time
Save state on applicationWillTerminate:
Memory management
No swap device, minimal RAM
Use AutoreleasePools whenever objects are allocated in tight loops
Use lazy algorithms as much as possible
Free up memory when app receives low memory warning
52
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Application Environment
Apps quit when user switches to another app
Important to start and stop quickly
No background processing after quit
Apps can't access filesystem outside their own sandbox
Try to limit total app size to < 10MB
Users should be able to download in reasonable amount of time
53
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Memory Constraints
256 MB of RAM available to OS + apps on 3G S, 128MB on older devices
Memory must be managed more carefully
Garbage collection not available
Apps get memory warnings when consuming too much RAM
Rule of thumb is 20MB of real memory
App should be prepared to free up RAM by clearing caches, etc.
54
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
MVC
Cocoa and Cocoa Touch UI based on Model-View-Controller
Model objects encapsulate app data, business logic
UIKit provides View components
Windows, views, and controls
Apps can provide custom components
UIKit also provides controller classes
Apps generally provide custom subclasses
55
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
App Architecture
NSRunLoop
Main application event loop
Modal loops
Event and drawing cycle
OS enqueues events generated by user input, network, etc.
Application pulls events off queue and dispatches
At end of event loop, Application propagates message to Views to draw themselves
56
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Graphics and Drawing
Window server connects app to rendering engine
Manages and renders all windows on behalf of apps
Core Graphics and Core Animation
Frameworks for 2D drawing and animation
Integrated with UIKit
OpenGL
Integrated with Core Animation
57
Friday, October 9, 2009
View Drawing
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Quartz
iPhone's 2D drawing engine
Can stroke and fill lines, polygons, text
Supports
Drawing and painting
Transparency, shadows, anti-aliasing
Shading and color management
PDF document creation and metadata access
59
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Framework Drawing Behavior
At the end of each event cycle, framework propagates -display message down the view hierarchy
If a given view needs to redraw, -display makes callback to -drawRect:
You never call display directly; instead you can send setNeedsDisplay on a given UIView or CALayer that needs to be redrawn
However you rarely need to call this method; views usually know when they need to be redrawn
To implement custom drawing, override -drawRect: in a subclass of UIView
Override -drawInContext: for subclasses of CALayer
60
Friday, October 9, 2009
Views and Layers
UIView has subviews property
NSArray of nested UIView instances
Subviews are drawn on top of parent view (superview) in the order in which they appear in the subviews array
UIView also layer property of type CALayer *
CALayer is like a lightweight UIView
Has sublayers property for nested CALayer instances
Very efficient for animation; 100s of layers can be animated simultaneously
Friday, October 9, 2009
View-Layer Hierarchy
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Drawing Text
UIView is responsible for drawing everything rendered to the screen
Subclasses can override drawRect: to customize drawing behavior for classes that do their own drawing
UIKit adds category to NSString (UIStringDrawing)
Methods draw in the current graphics context using current color
Take instance of UIFont as an argument
- drawAtPoint:withFont:
- drawInRect:withFont:
63
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Text Drawing Example
In a subclass of UIView:
64
- (void)drawRect:(CGRect)rect{ NSString *text = @"Hello, World!"; CGPoint startingPoint = CGPointMake(20.0, 40.0);
[[UIColor whiteColor] set]; UIFont *font = [UIFont systemFontOfSize:36.0]; [text drawAtPoint:startingPoint withFont:font];}
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Lab Exercise
Modify your app to draw "Hello World!" on the screen
Create a subclass of UIView called MyHelloView
Implement drawRect: to draw the text
Add an instance of your custom subclass to your app delegate's window (hint: use addSubview:)
65
Friday, October 9, 2009
© Copyright 2008 About Objects, Inc. All rights reserved worldwide.
Resources
Example Code:
http://www.aboutobjects.com/tutorials.html
Documentation:
Objective-C: http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.html
iPhone: http://developer.apple.com/iphone/library/navigation/index.html
Courses:
http://www.aboutobjects.com/training/courses.html
66
Friday, October 9, 2009