Objective c and Java

  • Upload
    djilo

  • View
    224

  • Download
    0

Embed Size (px)

Citation preview

  • 8/6/2019 Objective c and Java

    1/69

    AboutObjects

    Objective-C and

    Java: a

    Comparison

    PART 1

    Developeroriented training.

    www.AboutObjects.com

    http://www.aboutobjects.com/http://www.aboutobjects.com/
  • 8/6/2019 Objective c and Java

    2/69

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

    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 ofJakarta Pitfalls andMastering JavaServer Faces

    Now: iPhone developer and trainer

    2

  • 8/6/2019 Objective c and Java

    3/69

    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

  • 8/6/2019 Objective c and Java

    4/69

  • 8/6/2019 Objective c and Java

    5/69

  • 8/6/2019 Objective c and Java

    6/69

    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

  • 8/6/2019 Objective c and Java

    7/69

    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 orprofit in spare time

    Trust meIt is a lot of fun!

    7

  • 8/6/2019 Objective c and Java

    8/69

    History

  • 8/6/2019 Objective c and Java

    9/69

  • 8/6/2019 Objective c and Java

    10/69

    NeXT, Inc.'s NeXTCUBE

  • 8/6/2019 Objective c and Java

    11/69

    NEXTSTEP Timeline

    1989 NEXTSTEP 1.0

    1992 NEXTSTEP 486 for Intel

    1994 NeXT/Sun OpenStep spec.

    1996 OPENSTEP 4.0 released

  • 8/6/2019 Objective c and Java

    12/69

    Apple + NeXT

    Late 1996

    Apple's Copland stalls

    Goal had been to develop modern OS

    to replace Mac OS 9Apple 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

  • 8/6/2019 Objective c and Java

    13/69

    What Apple Bought in 1996

  • 8/6/2019 Objective c and Java

    14/69

    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'

  • 8/6/2019 Objective c and Java

    15/69

  • 8/6/2019 Objective c and Java

    16/69

    Platforms

  • 8/6/2019 Objective c and Java

    17/69

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

    Comparing Platforms

    Java

    Almost everywhere

    ... except iPhone

    Objective-CMac OS X

    iPhone

    17

  • 8/6/2019 Objective c and Java

    18/69

    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

  • 8/6/2019 Objective c and Java

    19/69

    iPhone SDK

    Media

    Core OS

    Cocoa Touch

    Core Services

  • 8/6/2019 Objective c and Java

    20/69

    iPhone SDK

    Core Services

  • 8/6/2019 Objective c and Java

    21/69

    Core Services

    20

    Core Foundation C Library Strings, dates, collections, threads, etc.

    Address Book Framework Managing contact info

    CFNetworkC 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

  • 8/6/2019 Objective c and Java

    22/69

    Media

    iPhone SDK

    Core OS

    Cocoa Touch

    Core Services

  • 8/6/2019 Objective c and Java

    23/69

  • 8/6/2019 Objective c and Java

    24/69

    Media

    Open GL ES

    Core Graphics

    Core Animation

    Core Audio

  • 8/6/2019 Objective c and Java

    25/69

    iPhone SDK

    Cocoa Touch

    Media

    Core OS

    Core Services

  • 8/6/2019 Objective c and Java

    26/69

    iPhone SDK

    Cocoa Touch

  • 8/6/2019 Objective c and Java

    27/69

    Cocoa Touch

    UIKit

    Foundation Framework

  • 8/6/2019 Objective c and Java

    28/69

    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

  • 8/6/2019 Objective c and Java

    29/69

    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

  • 8/6/2019 Objective c and Java

    30/69

    Developer Tools

  • 8/6/2019 Objective c and Java

    31/69

    XCode

    IDE for iPhone Projects

    Build

    Run (Simulator, device)

    Debug

    Source code management (SCM)

    Documentation

  • 8/6/2019 Objective c and Java

    32/69

    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 coarsergranularity

    Linked at compile time; no classpath needed

  • 8/6/2019 Objective c and Java

    33/69

    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

  • 8/6/2019 Objective c and Java

    34/69

    Instruments

    Profiling

    Performance Monitoring

    Garage-Band 'multi-track' interface

    Profiling

    Performance Monitoring

    Garage-Band 'multi-track' interface

  • 8/6/2019 Objective c and Java

    35/69

    Syntactic Differences

  • 8/6/2019 Objective c and Java

    36/69

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

    Message Syntax

    Square brackets for message expressions

    Java:

    myString.toString()

    Objective-C

    [myString description]

    33

  • 8/6/2019 Objective c and Java

    37/69

    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

  • 8/6/2019 Objective c and Java

    38/69

    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

  • 8/6/2019 Objective c and Java

    39/69

    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

  • 8/6/2019 Objective c and Java

    40/69

    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

  • 8/6/2019 Objective c and Java

    41/69

    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 avoidcollisions

    Java:

    java.lang.String s = new String("hello");

    Objective-C

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

    38

  • 8/6/2019 Objective c and Java

    42/69

    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

  • 8/6/2019 Objective c and Java

    43/69

    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

  • 8/6/2019 Objective c and Java

    44/69

  • 8/6/2019 Objective c and Java

    45/69

    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

  • 8/6/2019 Objective c and Java

    46/69

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

    #import

    @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

  • 8/6/2019 Objective c and Java

    47/69

    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

  • 8/6/2019 Objective c and Java

    48/69

    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

  • 8/6/2019 Objective c and Java

    49/69

  • 8/6/2019 Objective c and Java

    50/69

    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

  • 8/6/2019 Objective c and Java

    51/69

    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

  • 8/6/2019 Objective c and Java

    52/69

    Memory Management

  • 8/6/2019 Objective c and Java

    53/69

    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

  • 8/6/2019 Objective c and Java

    54/69

    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 wordcopy

    Calls to these methods or to retain must be paired with calls to releaseor autorelease. You never call dealloc directly.

    51

  • 8/6/2019 Objective c and Java

    55/69

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

    // Deallocate anything we've retained or copied

    - (void)dealloc{

    [_firstNamerelease];[superdealloc];

    }

    - (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{

    [_firstNamerelease]; // Release the previous one

    _firstName = [firstName copy]; // Retain or copy the new one}

    }

    Managing Reference Counts

    52

  • 8/6/2019 Objective c and Java

    56/69

    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

  • 8/6/2019 Objective c and Java

    57/69

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

    Synthesizing Accessor Methods

    Declared properties allow compiler to synthesize getter/settermethods

    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

  • 8/6/2019 Objective c and Java

    58/69

    Foundation Framework

  • 8/6/2019 Objective c and Java

    59/69

    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

  • 8/6/2019 Objective c and Java

    60/69

    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

  • 8/6/2019 Objective c and Java

    61/69

    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

  • 8/6/2019 Objective c and Java

    62/69

    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

  • 8/6/2019 Objective c and Java

    63/69

    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

  • 8/6/2019 Objective c and Java

    64/69

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

    int main (int argc, constchar *argv[])

    { NSAutoreleasePool * pool = [[NSAutoreleasePoolalloc] init];

    NSError *readError = nil; NSURL *url = [NSURLURLWithString:@"http://www.apple.com"];

    NSString *htmlString = [NSStringstringWithContentsOfURL: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];

    return0;

    }

    61

  • 8/6/2019 Objective c and Java

    65/69

    Categories

  • 8/6/2019 Objective c and Java

    66/69

    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

  • 8/6/2019 Objective c and Java

    67/69

    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 ([selfcount] == 0)

    returnnil;

    return [selfobjectAtIndex:0];}

    - (id)nicestGuy

    {

    for (NSString *currStr inself) {

    if ([currStr hasPrefix:@"J"])

    return currStr;}

    returnnil;}

    @end

    Example: Category on NSArray

    64

  • 8/6/2019 Objective c and Java

    68/69

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

    #import

    #import "NSArray+MyExtensions.h"

    int main (int argc, constchar * argv[])

    { NSAutoreleasePool * pool = [[NSAutoreleasePoolalloc] init];

    NSArray *a = [NSArrayarrayWithObjects:@"Fred", @"Joe", @"Bob", nil];

    NSLog(@"First object: %@", [a firstObject]); NSLog(@"Nicest guy: %@", [a nicestGuy]);

    [pool drain];

    return0;

    }

    Example: Using Category

    65

  • 8/6/2019 Objective c and Java

    69/69