Sei sulla pagina 1di 69

About Objects

www.AboutObjects.com

Objective-C and Java: a Comparison


PART 1

Developeroriented training.

About the Speaker


Jonathan Lehr, About Objects 19912001: Objective-C developer and trainer
NEXTSTEP (precursor to Mac OS X and Cocoa) WebObjects (web app framework and ORM)

20012008: 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

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

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

Overview

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)

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.)

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 prot in spare time
Trust meIt is a lot of fun!

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

History

Where Did Objective-C Come From?


Inspired by SmallTalk
1972 Alan Kay, Xerox PARC Alto workstation

Xerox Alto

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)

NeXT, Inc.'s NeXTCUBE

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

What Apple Bought in 1996

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+ le 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

Platforms

Comparing Platforms
Java
Almost everywhere ... except iPhone

Objective-C
Mac OS X iPhone

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

17

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)

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

18

iPhone SDK
Cocoa Touch Media Core Services Core OS

iPhone SDK
Cocoa Touch Media Core Services Core OS

Core Services
Core Foundation Address Book CFNetwork Core Location Security SQLite XML Support
C Library Framework C Library Framework Framework C Library ObjC Class Strings, dates, collections, threads, etc. Managing contact info Low-level network access Accessing geospatial positioning info Manages certicates, public/private keys, etc. Accessing lightweight SQL database NSXMLParser class

20

iPhone SDK
Cocoa Touch Media Core Services Core OS

iPhone SDK
Cocoa Touch Media Core Services Core OS

Media
Core Animation Open GL ES Core Graphics Core Audio

iPhone SDK
Cocoa Touch Media Core Services Core OS

iPhone SDK
Cocoa Touch Media Core Services Core OS

Cocoa Touch

UIKit Foundation Framework

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)

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

25

UIKit
Application management and integration (via URL schemes) Graphics and windowing Handling touch events User interface views and controls Text handling Web content Device-specic features (accelerometer, camera, photo library)

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

26

Developer Tools

XCode
IDE for iPhone Projects
Build Run (Simulator, device) Debug Source code management (SCM) Documentation

Xcode
Automatically maintains build scripts Displays logical groupings of les
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 les Dynamically loaded Objects deserialized at load time

Instruments
Proling Performance Monitoring Garage-Band 'multi-track' interface

Syntactic Differences

Message Syntax
Square brackets for message expressions Java:
myString.toString()

Objective-C
[myString description]

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

33

Method Arguments
Arguments are delimited by colons Java:
person.setFirstName("Fred");

Objective-C
[person setFirstName:@"Fred"];

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

34

Constants
Constant string object different from constant string Java:
"Hello"

Objective-C
@"Hello" "Hello" // String object // C string

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

35

Object Data Types


Objective-C objects are dynamically allocated structs Variable types are therefore pointers to struct dened 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];

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

36

Constructors vs. Creation Methods


No constructors; creation methods are just methods
Ordinary return statements provide more exibility 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];

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

37

Prex vs. Package Path


Obj-C language doesn't provide namespaces Frameworks and libraries use prexes by convention to avoid collisions Java:
java.lang.String s = new String("hello");

Objective-C
NSString *s = [[NSString alloc] initWithString:"hi"];

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

38

Method Prototypes
Methods declared in .h, implemented in .m Data types enclosed in parens Instance methods prexed with Class methods prexed with +
// Method declarations - (id)init; + (id)alloc;

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

39

No Method Overloading
Runtime system looks up methods by name rather than signature
Makes introspection simpler and more efcient

Java:
manager.addEmployee(emp); manager.addEmployee(emp, "Developer");

Objective-C
[manager addEmployee:emp]; [manager addEmployee:emp withTitle:@"Developer"];

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

40

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

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

41

Classes
Two separate les
Declared in .h le Implemented in .m le

Compiler directives
@interface ... @end @implementation ... @end

Curly braces
Instance variable section inside curly braces Methods dened outside curly braces

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

42

Class Declaration

#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

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

43

Anatomy of a Class Declaration


compiler directive class we're declaring class it inherits from

@interface Person : NSObject { int _age; NSString * _firstName; } ... @end data type name of instance variable

Class Declaration: Methods


@interface Person : NSObject { ... // Instance variables go here } // Method declarations start here... - (int)age; method name arg name

- (void) setAge: (int)anAge; return type ... @end arg type

Class Implementation
#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

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

46

Visibility Modiers
Compiler directives
@private @protected @public

No visibility modiers for methods


Methods made 'private' by omitting declarations from .h le. To emphasize 'privacy', prex method name with underscore.

Intent:
Obj-C: Makes obvious what you shouldn't do Java: Makes impossible what you shouldn't do
Copyright 2009 About Objects, Inc. All rights reserved worldwide.

47

Visibility Modiers

@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

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

48

Memory Management

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

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

50

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.

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

51

Managing Reference Counts


// 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 } }

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

52

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;

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

53

Synthesizing Accessor Methods


Declared properties allow compiler to synthesize getter/setter methods
Add the following after @implementation in .m le:

@synthesize firstName = _firstName; Equal sign and ivar name can be omitted if ivar name is the same as getter name

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

54

Foundation Framework

NSObject
Implements introspection Implements protocols for important mechanisms
Key-Value Coding (NSKeyValueCoding) Key-Value Observing (NSKeyValueObserving)

Denes protocols for copying and serialization


NSCopying NSMutableCopying NSCoding

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

56

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"];

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

57

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];

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

58

Reading/Writing Files and URLs


Strings and Collections know how to read and write themselves
To and from les in the lesystem To and from URLs

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

59

NSDictionary
Similar to HashMap in Java Mutable vs. immutable Read and write itself as plist le

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

60

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; }

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

61

Categories

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

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

63

Example: Category on NSArray


@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

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

64

Example: Using Category

#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; }

Copyright 2009 About Objects, Inc. All rights reserved worldwide.

65

Questions?

Potrebbero piacerti anche