Upload
vanthuan
View
241
Download
0
Embed Size (px)
Citation preview
About Objects
Objective-C and
Java: a
Comparison
PART 1
Developer–oriented training.
www.AboutObjects.com
© 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
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
About Objects
Reston Town Center (Accenture Building)
iPhone OS and MacOS X
Training
Development
Core Curriculum
ANSI C Programming
Objective-C Programming
Cocoa Programming Workshop
iPhone Programming Workshop
3
© 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
© 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
© 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
Where 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
NEXTSTEP Timeline
1989 – NEXTSTEP 1.0
1992 – NEXTSTEP 486 for Intel
1994 – NeXT/Sun OpenStep spec.
1996 – OPENSTEP 4.0 released
Apple + 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
From OpenStep to Mac
OS X
Mac OS X 10.0
March, 2001
Initial release of OS X
Port of OpenStep
+ Mac Toolbox APIs
+ 'Mac-like' UI tweaks
+ HFS+ file system
+ Mac OS 9 compatibility environment
+ Quartz rendering engine
Replacement for Display Postscript
+ Objective-C UI layer rebranded 'Cocoa'
iPhone 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
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
Comparing Platforms
Java
Almost everywhere
... except iPhone
Objective-C
Mac OS X
iPhone
17
© 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)
Foundation framework
UI framework
AppKit (Mac OS)
UIKit (iPhone OS)
18
Core 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
© 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
© 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
XCode
IDE for iPhone Projects
Build
Run (Simulator, device)
Debug
Source code management (SCM)
Documentation
Xcode
Automatically maintains build scripts
Displays logical groupings of files
No package paths
By default, groups not mapped to folder
structure
Resources
Automatically bundled with executable
Frameworks
Rough equivalent of JARs but at much coarser
granularity
Linked at compile time; no classpath needed
Interface 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
Instruments
Profiling
Performance Monitoring
Garage-Band 'multi-track' interface
Profiling
Performance Monitoring
Garage-Band 'multi-track' interface
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
Message Syntax
Square brackets for message expressions
Java:
myString.toString()
Objective-C
[myString description]
33
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
Method Arguments
Arguments are delimited by colons
Java:
person.setFirstName("Fred");
Objective-C
[person setFirstName:@"Fred"];
34
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
Constants
Constant string object different from constant string
Java:
"Hello"
Objective-C
@"Hello" // String object
"Hello" // C string
35
© 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
© 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
Inheritance is straight-forward
Memory allocation and initialization are separate steps
Java:
Employee emp = new Employee();
Objective-C
Employee *emp = [[Employee alloc] init];
37
© 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 collisions
Java:
java.lang.String s = new String("hello");
Objective-C
NSString *s = [[NSString alloc] initWithString:"hi"];
38
© 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
© 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
Java:
manager.addEmployee(emp);
manager.addEmployee(emp, "Developer");
Objective-C
[manager addEmployee:emp];
[manager addEmployee:emp withTitle:@"Developer"];
40
© 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
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
Classes
Two separate files
Declared in .h file
Implemented in .m file
Compiler directives
@interface ... @end
@implementation ... @end
Curly braces
Instance variable section inside curly braces
Methods defined outside curly braces
42
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
#import <Foundation/Foundation.h>
@interface Person : NSObject
{ // Instance variables. Underscore prefix conventional, but not required.
int _age;
NSString *_firstName;}
// Instance methods. Getter methods cannot be prefixed with 'get'.
- (int)age;
- (void)setAge:(int age);
- (NSString *)firstName;- (void)setFirstName:(NSString *)firstName;
@end
Class Declaration
43
Anatomy 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 variabledata type
Class Declaration: Methods
@interface Person : NSObject
{
... // Instance variables go here
}
// Method declarations start here...
- (int)age;
- (void) setAge: (int)anAge;
...
@end
return type
method name
arg type
arg name
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
#import "Person.h"
@implementation Person
- (int)age {
return _age;}
- (void)setAge:(int age) {
_age = age;}
- (NSString *)firstName {
return firstName;}
- (void)setFirstName:(NSString *)firstName {
// Note: Omits some memory management details... _firstName = firstName;
}
@end
Class Implementation
46
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
Visibility Modifiers
Compiler directives
@private
@protected
@public
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
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
@interface Person : NSObject
{
// Visibility modifier. Applies to all ivars that follow.@private
// Private instance variables. NSString *_firstName;
NSNumber *_salary;
@protected // Protected instance variables.
int _age; }
// Instance methods.
...
@end
Visibility Modifiers
48
© 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
© 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
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
// Deallocate anything we've retained or copied
- (void)dealloc{
[_firstName release]; [super dealloc];
}
- (NSString *)firstName{
return [[firstName copy] autorelease]; // Will be released after calling method completes
}
- (void)setFirstName:(NSString *)firstName{
if (firstName != _firstName) // Avoid messing up the retain count {
[_firstName release]; // Release the previous one
_firstName = [firstName copy]; // Retain or copy the new one }
}
Managing Reference Counts
52
© 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
© 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
© 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
© 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
© 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
© 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
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
NSDictionary
Similar to HashMap in Java
Mutable vs. immutable
Read and write itself as plist file
60
© 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
encoding:NSUTF8StringEncoding error:&readError];
if (readError) { NSLog(@"Unable to read URL: %@ due to error: %@", url, readError);
}
NSLog(@"HTML string: %@", htmlString);
NSError *writeError = nil; NSString *path = @"/tmp/Apple.html";
[htmlString writeToFile:path atomically:YES
encoding:NSUTF8StringEncoding error:&writeError];
if (writeError) {
NSLog(@"Unable to write file at path: %@", path); }
[pool drain];
return 0;}
61
© 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
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
@interface NSArray (MyExtensions) // In .h file
- (id)firstObject;- (id)nicestGuy;
@end...
@implementation NSArray (MyExtensions) // In .m file- (id)firstObject
{ if ([self count] == 0)
return nil;
return [self objectAtIndex:0];}
- (id)nicestGuy
{ for (NSString *currStr in self) {
if ([currStr hasPrefix:@"J"]) return currStr;
}
return nil;}
@end
Example: Category on NSArray
64
© Copyright 2009 About Objects, Inc. All rights reserved worldwide.
#import <Foundation/Foundation.h>
#import "NSArray+MyExtensions.h"
int main (int argc, const char * argv[]){
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSArray *a = [NSArray arrayWithObjects:@"Fred", @"Joe", @"Bob", nil];
NSLog(@"First object: %@", [a firstObject]); NSLog(@"Nicest guy: %@", [a nicestGuy]);
[pool drain];
return 0;}
Example: Using Category
65