Documente Academic
Documente Profesional
Documente Cultură
Objective-C on iPhone OS
Blaine Garst
Wizard of Runtimes
2
Working Effectively with
Objective-C on iOS 4
Blaine Garst
Wizard of Runtimes
3
Objective-C is the language of Cocoa Touch.
Take an in-depth working tour of Objective-C,
from properties and memory management, to
integrating your existing C and C++ code with
Objective-C. Examine design patterns, exception
models, and other important considerations. A
valuable session to hone your knowledge of the
language.
4
LISP/Scheme
C Syntax: Statements, Control Flow, Operators
Objective-C Exceptions
Closures (ObjC: Blocks)
C++
Java Primitives: Numbers, Strings
C#
Aggregates: Structures, Objects
Ruby
Objective-C Inheritance
Python Interfaces (ObjC: Protocols)
JavaScript Accessors
PHP
Collections: Lists, Arrays, Sets, Maps
Perl
OCaml Platform: Memory Management
Haskell Input/Output
Erlang
Go
5
Territory
6
Syntax: Statements, Control Flow, Operators
Exceptions
Closures (ObjC: Blocks)
C
Objective-C
C++
7
Blocks
8
iOS 4 Block APIs
typedef void (^ALAssetsGroupEnumerationResultsBlock)(ALAsset *result, NSUInteger index, BOOL *stop);
typedef void (^ALAssetsLibraryGroupsEnumerationResultsBlock)(ALAssetsGroup *group, BOOL *stop);
typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);
typedef void (^ALAssetsLibraryWriteImageCompletionBlock)(NSURL *assetURL, NSError *error);
typedef void (^ALAssetsLibraryWriteVideoCompletionBlock)(NSURL *assetURL, NSError *error);
typedef void (^AudioQueueOutputCallbackBlock)(
typedef void (^AudioQueueInputCallbackBlock)(
- (void)exportAsynchronouslyWithCompletionHandler:(void (^)(void))handler;
typedef void (^AVAssetImageGeneratorCompletionHandler)(CMTime requestedTime, CGImageRef image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error);
- (void)loadValuesAsynchronouslyForKeys:(NSArray *)keys completionHandler:(void (^)(void))handler;
- (void)captureStillImageAsynchronouslyFromConnection:(AVCaptureConnection *)connection completionHandler:(void (^)(CMSampleBufferRef imageDataSampleBuffer, NSError *error))handler;
- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block;
- (id)addBoundaryTimeObserverForTimes:(NSArray *)times queue:(dispatch_queue_t)queue usingBlock:(void (^)(void))block;
CF_EXPORT void CFRunLoopPerformBlock(CFRunLoopRef rl, CFTypeRef mode, void (^block)(void)) CF_AVAILABLE(10_6, 4_0);
typedef void (^CMAccelerometerHandler)(CMAccelerometerData *accelerometerData, NSError *error);
10
Repeat Block N Times Function
NSMutableString *str = [NSMutableString string];
..
repeat(12, ^{
[str appendFormat:@"rand: %d ", rand()];
});
11
Block Literal Syntax Summary
Return
Arguments Body
Type
12
About Blocks…
•Introducing
Start out Blocks
on stack—fast!
and Grand Central Dispatch on iPhone Russian Hill
Wednesday 11:30AM
__block id keyForValue = nil;
• Blocks are objects!
Advanced Objective-C and Garbage[dict enumerateKeysAndObjectsUsingBlock:
Collection Techniques Pacific Heights
Friday 11:30AM
^ (id key, id value, BOOL *stop) {
• Can be copied to heap! if ([object isEqual:sought)]) {
■ [^{...} copy] keyForValue = key;
*stop = YES;
■ [block release]
}
}];
• Used for
■ Enumerations
■ Callback notifications
13
Cocoa Touch Iteration Best Practice
For enumerations that need more than one value at a time, use the collection Block APIs:
[dict enumerateKeysAndObjectsUsingBlock:
^(id k, id obj, BOOL *stop) { ..k..obj.. }];
14
C
Objective-C
C++
Objective-C++
15
Objective-C++
MyMixedClass.mm
@class MyUIKitWidget; • Mix and match:
class MyEngine { ■ Instance/Member variables
MyUIKitWidget *widget;
■ Statements
};
■ Declarations
@interface MyUIKitWidget : NSObject {
MyEngine eng; ■ Exceptions
}
@end ■ Whole Classes
@implementation MyUIKitWidget
- (id)myUIKitWidgetMethod {
MyEngine ff;
throw [NSException new];
• CAN’T mix methods/functions
}
return nil; • CAN’T subclass one from another
16
Objects
Inheritance
17
Table replaces code
~destructor -dealloc
18
Protocols (Java: interface)
SWIMMER FLYER MACHINE
multiple-inheritance -swim -fly -start
of abstract methods NSOBJECT
-hash
ANIMAL AIRPLANE
-hash -hash
-parents -fly
Classes -start
single-inheritance
of instance variables
FISH BIRD
-hash -hash
-parents -parents
-swim -fly
DUCK
-hash
-parents @interface Duck : Bird <Swimmer, Flyer>
-swim
-fly
19
Apple Provided Your Application
20
Categories
21
Memory Management
22
Memory Management: The Basics
23
Directed Acyclic Graph
01
01 01
01 01 01
1
01 01 02
02 01
01
12
01
1
01
24
Directed Acyclic Graph
25
Cyclic Graph
1 1 2
2 1
2
1
1
1
26
Simple Rules
2
• Release old and
1
1
■ Retain new values,
1
■ Unless from -initXXX or -copy
1
27
How Autorelease Pools Work
@implementation NSDate
...
+ (id) date { d
return [[[self alloc] init] autorelease]; tmp
}
...
@end
while (1) {
NSEvent *event = getEvent();
event e
id pool = [NSAutoreleasePool new];
process(event); pool
[pool drain];
} Autorelease Pool
Stack
28
How Autorelease Pools Work
while (1) {
NSEvent *event = getEvent();
event e
id pool = [NSAutoreleasePool new];
process(event); pool
[pool drain];
} Autorelease Pool
Stack
29
How Autorelease Pools Work
while (1) {
NSEvent *event = getEvent();
event e
id pool = [NSAutoreleasePool new];
process(event); pool
[pool drain];
} Autorelease Pool
Stack
30
Accessors
31
Cocoa Getter/Setter Pattern
@implementation CustomObject
- (int) balance { return balance; }
CustomObject.m: - (void) setBalance:(int)newBalance {
balance = newBalance;
}
@end
32
Properties: Automatic Declaration and Methods
WWDC2010: 32-bit simulator uses modern runtime!
@implementation CustomObject
CustomObject.m: @synthesize
// @synthesize
balance;
by default!!
@end // Xcode 4 LLVM 2.0 Compiler!!
Pacific Heights
Advanced Objective-C and Garbage Collection Techniques Friday 11:30AM
33
Property Attributes
Attributes define allowable behaviors
34
All Attributes
35
Property Implementations
You can explicitly code any or all parts of an @property
@implementation CustomObject
- (int) balance { return secretBalance; }
- (void) setBalance:(int)newBalance {
secretBalance = newBalance;
}
@end
36
Property Implementations
Can designate backing instance variable with @synthesize
@implementation CustomObject
@synthesize balance=secretBalance;
@end
37
Deferred Implementation
Must use @dynamic
@implementation CustomObject
@dynamic balance;
@end
Pacific Heights
Advanced Objective-C and Garbage Collection Techniques Friday 11:30AM
38
@property(copy) Getter/Setter Pattern
- (NSString *) title {
@synchronized(self) {
return [[title retain] autorelease];
}
}
- (void) setTitle:(NSString *)newTitle {
@synchronized(self) {
NSString *tmp = [newTitle copy];
[title release];
title = tmp;
}
}
- (void) dealloc {
[title release]; // or self.title = nil;
[super dealloc];
}
39
Cocoa Patterns
40
Selectors
- (void) aMethod:(id)object {
if ([object respondsToSelector:@selector(fred)])
[object fred];
}
41
Delegation—Your Part
@implementation MyDelegate
- (void)setUp {
uiactionsheet.delegate = self;
}
- (void)willPresentActionSheet:(UIActionSheet *)as {
...
}
...
42
Delegation—UIKit Part
43
Class Clusters
NSString
44
“Property List” Abstract Value Classes
NSObject
45
Abstract Mutable Value Class Pattern
-mutableCopy -copy
-mutableCopy -copy
46
Wrap-up?
Summary?
Wrap-up Reivew?
spelling of Wrap
Up?
47
Related Sessions and Labs
Russian Hill
Introducing Blocks and Grand Central Dispatch on iPhone Wednesday 11:30AM
Marina
API Design for Cocoa and Cocoa Touch Thursday 4:30PM
Pacific Heights
Advanced Objective-C and Garbage Collection Techniques Friday 11:30AM
48
More Information
Michaelopolis Jurewitz
Developer Tools Evangelist
jurewitz@apple.com
49
Q&A
50
51
52
53