11. Why Concurrency?
With a single thread,long-running operations may
interfere with user interaction
Multiple threads allow you to load resources or
perform computations without locking
up your entire application
12年12月23⽇日星期⽇日
12. Threads on the iOS
Based on the POSIX threading API
/usr/include/pthread.h
Higher-level wrappers in the Foundation
framework(NSSThread)
12年12月23⽇日星期⽇日
13. NSThread Basics
Run loop automatically instantiated for each
thread
Each NSThread needs to create its own
autorelease pool
Convenience methods for messaging between
threads
12年12月23⽇日星期⽇日
14. Sample
- (void)someAction:(id)sender
{
// Fire up a new thread
[NSThread detachNewThreadSelector:@selector(doWork:)
withTarget:self object:someData];
}
- (void)doWork:(id)someData
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[someData doLotsOfWork];
// Message back to the main thread
[self performSelectorOnMainThread:@selector(allDone:)
withObject:[someData result] waitUntilDone:NO]; //同步主线程
[pool release];
}
12年12月23⽇日星期⽇日
15. UIKit and Threads
Unless otherwise noted, UIKit classes are not
threadsafe
Objects must be created and messaged from the
main thread
12年12月23⽇日星期⽇日
21. basic
Abstract superclass
Manages thread creation and lifecycle
Encapsulate a unit of work in an object
•Specify priorities and dependencies
12年12月23⽇日星期⽇日
22. NSOperationQueue
Operations are typically scheduled by adding to a
queue
Choose a maximum number of concurrent
operations
Queue runs operations based on priority and
dependencies
12年12月23⽇日星期⽇日
25. Key-Value Coding (KVC)
•Get/set a value on an object by key (a string)
•First attempts to access via KVC-Compliant getters/setters
•If that fails, attempts to get to value directly
Key Paths
•Traverse objects using dot-separated keys
•Ex: @”person.address.street”
•Must use “keyPath” methods, instead of “key” methods to
automatically parse the string
- (id)valueForKeyPath:(NSString *)keyPath;
- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
12年12月23⽇日星期⽇日
26. Accessing Undefined Keys
•What if you try to access a key that is undefined?
■NSUndefinedKeyException
•But you can override!
-(id)valueForUndefinedKey:(NSString *)key;
-(void)setValue:(id)value forUndefinedKey:
(NSString *)key;
12年12月23⽇日星期⽇日
27. Key-Value Observing (KVO)
•Listen for changes to an object’s KVC-compliant values
•NSObject automatically broadcasts changes to observers
•No changes required to object being listened to
12年12月23⽇日星期⽇日
68. Resource
Session 102 - What's New in Foundation for
iOS 4
Session 110 - Advanced Text Handling for
iPhone OS
Session 206 - Introducing Blocks and
Grand Central Dispatch on iPhone
Session 211 - Simplifying iPhone App
Development with Grand Central Dispatch
12年12月23⽇日星期⽇日