All rights reserved worldwide.About the Speaker Jonathan Lehr, About Objects 1991–2001: Objective-C developer and trainer NEXTSTEP precursor to Mac OS X and Cocoa WebObjects web app fra
Trang 2© Copyright 2009 About Objects, Inc All rights reserved worldwide.
About the Speaker
Jonathan Lehr, About Objects
1991–2001: Objective-C developer and trainer
NEXTSTEP (precursor to Mac OS X and Cocoa)
WebObjects (web app framework and ORM)
2001–2008: Java EE developer
Fannie Mae and US Govt web app projects
Framework developer
Co-author of Jakarta Pitfalls and Mastering JavaServer Faces
Now: iPhone developer and trainer
2
Trang 3© Copyright 2009 About Objects, Inc All rights reserved worldwide.
About Objects
Reston Town Center (Accenture Building)
iPhone OS and MacOS X
Cocoa Programming Workshop
iPhone Programming Workshop
3
Trang 4Overview
Trang 5© Copyright 2009 About Objects, Inc All rights reserved worldwide.
What is Objective-C?
Superset of ANSI C
Adds object-oriented capabilities to C language
Runtime system (C library)
Dynamic typing
Dynamic binding
GNU C compiler compiles C and Objective-C
Apple donated Objective-C to GNU project (open source)
5
Trang 6© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Who Uses Objective-C?
Primarily Apple
Mac OS X
Cocoa (UI framework)
Several other smaller frameworks (Core Animation, Core Data, etc.)
iPhone OS
Cocoa touch (UI framework)
Several other smaller frameworks (Core Animation, Core Data, etc.)
6
Trang 7© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Why Should I Care (as a Java Dev)?
Cool approaches to problems can open door to new design ideas
Some enterprise projects may need to integrate with iPhone apps
Doesn't hurt to have more perspective on how client apps work
Enterprises starting to write custom iPhone apps
Managers might ask you for technical info, opinions
Might even draft you for an iPhone development effort
Might want to tinker with iPhone app development for fun or
profit in spare time
Trust me—It is a lot of fun!
7
Trang 8History
Trang 9Where Did Objective-C
Come From?
Inspired by SmallTalk
1972 – Alan Kay, Xerox PARC
Alto workstation
First Objective-C compiler
1983 – Brad Cox, StepStone
First major licensee
1985 – Steve Jobs, NeXT Computer
Used to develop UI for NEXTSTEP OS
(and later, OpenStep)
Xerox Alto
Trang 10NeXT, Inc.'s NeXTCUBE
Trang 11NEXTSTEP Timeline
1989 – NEXTSTEP 1.0
1992 – NEXTSTEP 486 for Intel
1994 – NeXT/Sun OpenStep spec.
1996 – OPENSTEP 4.0 released
Trang 12Apple + NeXT
Late 1996
Apple's Copland stalls
Goal had been to develop modern OS
to replace Mac OS 9
Apple decides to acquire third-party
OS instead
Buys NeXT, Inc for $440 million
Steve Jobs comes onboard as unpaid, part-time consultant
Result: NeXT takes over Apple
Trang 13What Apple Bought in 1996
Trang 14From OpenStep to Mac
+ Mac OS 9 compatibility environment
+ Quartz rendering engine
Replacement for Display Postscript + Objective-C UI layer rebranded 'Cocoa'
Trang 15iPhone OS
Port of Mac OS X
Shares same developer toolset
Developer frameworks adapted and scaled down for mobile device
iPhone OS 2.0b2
March, 2008
Initial release of iPhone OS
Trang 16Platforms
Trang 17© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Trang 18© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Layered Architecture
C libraries and system calls
Core Services (C libraries and Objective-C frameworks)
Media Layer (C libraries and Objective-C frameworks)
Cocoa (Mac OS) and Cocoa touch (iPhone OS)
Trang 21Core Services
20
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
Trang 24Open GL ES Core Graphics Core Animation
Core Audio
Trang 26iPhone SDK
Cocoa Touch Media
Core OS
Core Services
Trang 27Cocoa Touch
UIKit Foundation Framework
Trang 28© Copyright 2009 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)
25
Trang 29© Copyright 2009 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)
26
Trang 30Developer Tools
Trang 32Automatically maintains build scripts
Displays logical groupings of files
Trang 33Interface Builder
Visual GUI design tool
Doesn't generate code
Works with ‘Freeze-dried’ objects
Archived (serialized) in .nib files
Dynamically loaded
Objects deserialized at load time
Trang 35Syntactic Differences
Trang 36© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Trang 37© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Trang 38© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Trang 39© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Object Data Types
Objective-C objects are dynamically allocated structs
Variable types are therefore pointers to struct defined by class
Java:
Employee emp = new Employee();
Objective-C
Employee *emp = [[Employee alloc] init];
Obj-C also provides generic object type, id
id emp2 = [[Employee alloc] init];
36
Trang 40© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Constructors vs Creation Methods
No constructors; creation methods are just methods
Ordinary return statements provide more flexibility
Calls to super can occur anywhere within a method
Trang 41© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Prefix vs Package Path
Obj-C language doesn't provide namespaces
Frameworks and libraries use prefixes by convention to avoid
Trang 42© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Method Prototypes
Methods declared in h, implemented in m
Data types enclosed in parens
Instance methods prefixed with
-Class methods prefixed with +
// Method declarations
- (id)init;
+ (id)alloc;
39
Trang 43© Copyright 2009 About Objects, Inc All rights reserved worldwide.
No Method Overloading
Runtime system looks up methods by name rather than signature
Makes introspection simpler and more efficient
Trang 44© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Multi-Argument Methods
Method names can be composed of multiple sections
Each section ends with a colon that delimits the next arg
Java:
public void addEmployee(Employee emp, String title)
Objective-C
- (void)addEmployee:(Employee *)emp
withTitle:(NSString *)title
Name of method is addEmployee:withTitle:
Args are emp and title
41
Trang 45© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Instance variable section inside curly braces
Methods defined outside curly braces
42
Trang 46© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Trang 47Anatomy of a Class Declaration
@interface Person : NSObject {
int _age ; NSString * _firstName ; }
@end
compiler directive
class we're declaring class it inherits from
name of instance variable data type
Trang 48Class Declaration: Methods
@interface Person : NSObject {
// Instance variables go here
Trang 49© Copyright 2009 About Objects, Inc All rights reserved worldwide.
- ( void )setFirstName:( NSString *)firstName {
// Note: Omits some memory management details
Trang 50© Copyright 2009 About Objects, Inc All rights reserved worldwide.
No visibility modifiers for methods
Methods made 'private' by omitting declarations from h file
To emphasize 'privacy', prefix method name with underscore
Intent:
Obj-C: Makes obvious what you shouldn't do
Java: Makes impossible what you shouldn't do
47
Trang 51© Copyright 2009 About Objects, Inc All rights reserved worldwide.
@interface Person : NSObject
Trang 52Memory Management
Trang 53© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Garbage Collection
Objective-C 2.0 (Nov., 2007) provides GC on Leopard (OS X 10.5)
GC not available on iPhone for performance reasons
iPhone apps use autorelease pools and a built-in reference counting
system to provide partial automation
50
Trang 54© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Reference Counting
NSObject (root class) includes reference counting API
- (id)retain; // Increments retain count
- (id)release; // Decrements retain count
- (id)autorelease; // Delayed release
- (void)dealloc; // Called by release when retainCount == 0
Creation methods set retain count to 1
Methods whose names begin with alloc or new, or contain the word
copy
Calls to these methods or to retain must be paired with calls to release
or autorelease You never call dealloc directly.
51
Trang 55© Copyright 2009 About Objects, Inc All rights reserved worldwide.
// Deallocate anything we've retained or copied
[ _firstName release ]; // Release the previous one
_firstName = [firstName copy ]; // Retain or copy the new one
}
}
Managing Reference Counts
52
Trang 56© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Declared Properties (Obj-C 2.0)
Shorthand for declaration of getter/setter pair
@property (nonatomic, retain) NSString *firstName;
// The above line is a replacement for these two
- (NSString *)firstName;
- (void)setFirstName:(NSString *)firstName;
53
Trang 57© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Synthesizing Accessor Methods
Declared properties allow compiler to synthesize getter/setter
methods
Add the following after @implementation in m file:
@synthesize firstName = _firstName;
Equal sign and ivar name can be omitted if ivar name is the same as
getter name
54
Trang 58Foundation Framework
Trang 59© Copyright 2009 About Objects, Inc All rights reserved worldwide.
NSObject
Implements introspection
Implements protocols for important mechanisms
Key-Value Coding (NSKeyValueCoding)
Key-Value Observing (NSKeyValueObserving)
Defines protocols for copying and serialization
NSCopying
NSMutableCopying
NSCoding
56
Trang 60© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Mutable vs Immutable
NSMutableString is subclass of NSString
To obtain a mutable copy of an NSString:
NSString *s1 = @"Fred";
NSMutableString *s2 = [s1 mutableCopy];
[s2 appendString:@" Smith"];
Same pattern followed for other mutable/immutable class pairs
Example: NSArray and NSMutableArray
NSArray *a1 = [NSArray arrayWithObjects:@"One", @"Two", nil]; NSMutableArray *a2 = [a1 mutableCopy];
[a2 addObject:@"Three"];
57
Trang 61© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Value Classes
NSValue is wrapper class for primitive values and binary data
Subclasses: NSData, NSNumber, NSDecimalNumber
Simple API
NSNumber *n = [NSNumber numberWithFloat:3.5];
int x = [n intValue];
NSString also has simple API for primitive values
NSString *s = [NSString stringWithFormat:@"%f", 3.5];int x = [s intValue];
58
Trang 62© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Reading/Writing Files and URLs
Strings and Collections know how to read and write themselves
To and from files in the filesystem
To and from URLs
59
Trang 63© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Trang 64© Copyright 2009 About Objects, Inc All rights reserved worldwide.
int main ( int argc, const char *argv[])
{
NSAutoreleasePool * pool = [[ NSAutoreleasePool alloc ] init ];
NSError *readError = nil ;
NSURL *url = [ NSURL URLWithString : @"http://www.apple.com" ];
NSString *htmlString = [ NSString stringWithContentsOfURL :url
NSError *writeError = nil ;
NSString *path = @"/tmp/Apple.html" ;
[htmlString writeToFile :path
Trang 65Categories
Trang 66© Copyright 2009 About Objects, Inc All rights reserved worldwide.
Categories
Allow you to add methods to an existing class
Methods added to class at compile time (link phase)
Example: UIKit adds drawing methods to NSString
63
Trang 67© Copyright 2009 About Objects, Inc All rights reserved worldwide.
@interface NSArray (MyExtensions) // In h file
Trang 68© Copyright 2009 About Objects, Inc All rights reserved worldwide.
NSLog ( @"First object: %@" , [a firstObject ]);
NSLog ( @"Nicest guy: %@" , [a nicestGuy ]);
Trang 69Questions?