Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
www.AboutObjects.com
Developeroriented training.
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
Overview
What is Objective-C?
Superset of ANSI C Adds object-oriented capabilities to C language
Runtime system (C library) Dynamic typing Dynamic binding
iPhone OS
Cocoa touch (UI framework) Several other smaller frameworks (Core Animation, Core Data, etc.)
Might want to tinker with iPhone app development for fun or prot in spare time
Trust meIt is a lot of fun!
History
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
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
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)
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
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
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)
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]
33
Method Arguments
Arguments are delimited by colons Java:
person.setFirstName("Fred");
Objective-C
[person setFirstName:@"Fred"];
34
Constants
Constant string object different from constant string Java:
"Hello"
Objective-C
@"Hello" "Hello" // String object // C string
35
Objective-C
Employee *emp = [[Employee alloc] init];
36
Java:
Employee emp = new Employee();
Objective-C
Employee *emp = [[Employee alloc] init];
37
Objective-C
NSString *s = [[NSString alloc] initWithString:"hi"];
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;
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"];
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
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
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
43
@interface Person : NSObject { int _age; NSString * _firstName; } ... @end data type name of instance variable
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
46
Visibility Modiers
Compiler directives
@private @protected @public
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
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
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
51
52
// The above line is a replacement for these two... - (NSString *)firstName; - (void)setFirstName:(NSString *)firstName;
53
@synthesize firstName = _firstName; Equal sign and ivar name can be omitted if ivar name is the same as getter name
54
Foundation Framework
NSObject
Implements introspection Implements protocols for important mechanisms
Key-Value Coding (NSKeyValueCoding) Key-Value Observing (NSKeyValueObserving)
56
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];
58
59
NSDictionary
Similar to HashMap in Java Mutable vs. immutable Read and write itself as plist le
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; }
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
63
64
#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; }
65
Questions?