70
Networking & Multitasking 孔祥波 121223星期

Network and Multitasking

Embed Size (px)

DESCRIPTION

Networking, Multitasking GCD and block

Citation preview

Page 1: Network and Multitasking

Networking & Multitasking

孔祥波

12年12月23⽇日星期⽇日

Page 2: Network and Multitasking

network,tcp/ip,socket,CFNetWork

http, restful api

thread: posix thread, NSThread,NSOperation,push notification

Block and GCD

12年12月23⽇日星期⽇日

Page 3: Network and Multitasking

tcp/ip

20世纪六十年代 美国国防部

加州伯克利大学 BSD Unix

OSI 七层/TCP/IP四层模型

应用层http, pop3,smtp,ftp&

12年12月23⽇日星期⽇日

Page 4: Network and Multitasking

Socket

tcp/udp

tcp 三次握手

server/client 模型

server: open/bind/listen/connected/(send,recv)/close

client: open/bind/connect/(send,recv)/close

12年12月23⽇日星期⽇日

Page 5: Network and Multitasking

CFNetworkCFStream

RUNLoop base

CFReadStream create stream, set call back and runloop, call back read bytes

CFWriteStream

12年12月23⽇日星期⽇日

Page 6: Network and Multitasking

http

http protocol

Web service,SOAP,XML-RPC

Get RSS and ATOM feeds

download file

12年12月23⽇日星期⽇日

Page 7: Network and Multitasking

web service restful api

12年12月23⽇日星期⽇日

Page 8: Network and Multitasking

one more thing

12年12月23⽇日星期⽇日

Page 9: Network and Multitasking

debug network package

tcpdump -A -s0 -i en1 host hostnameand port 80

Wireshark network protocol dump

12年12月23⽇日星期⽇日

Page 10: Network and Multitasking

Multitasking

12年12月23⽇日星期⽇日

Page 11: Network and Multitasking

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⽇日星期⽇日

Page 12: Network and Multitasking

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⽇日星期⽇日

Page 13: Network and Multitasking

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⽇日星期⽇日

Page 14: Network and Multitasking

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⽇日星期⽇日

Page 15: Network and Multitasking

UIKit and Threads

Unless otherwise noted, UIKit classes are not threadsafe

Objects must be created and messaged from the main thread

12年12月23⽇日星期⽇日

Page 16: Network and Multitasking

debug

12年12月23⽇日星期⽇日

Page 17: Network and Multitasking

12年12月23⽇日星期⽇日

Page 18: Network and Multitasking

12年12月23⽇日星期⽇日

Page 19: Network and Multitasking

build thread- (void)threadDownload:(id)data{ NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init]; NSString *urlStr=@"http://www.apple.com/home/images/t_hero.png"; NSData *imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]]; UIImage *image=[UIImage imageWithData:imageData]; [self performSelectorOnMainThread:@selector(freshUIWith:) withObject:image waitUntilDone:YES]; [pool drain];}- (void)freshUIWith:(UIImage*)image{ self.imageView.image = image;}

12年12月23⽇日星期⽇日

Page 20: Network and Multitasking

NSOperation

12年12月23⽇日星期⽇日

Page 21: Network and Multitasking

basic

Abstract superclass

Manages thread creation and lifecycle

Encapsulate a unit of work in an object

•Specify priorities and dependencies

12年12月23⽇日星期⽇日

Page 22: Network and Multitasking

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⽇日星期⽇日

Page 23: Network and Multitasking

KVC/KVO

12年12月23⽇日星期⽇日

Page 24: Network and Multitasking

Key-Value Coding (KVC) •Access object values ■ NSString *name = person.name; ■ NSString *name = [person name]; ■ NSString *name = [person valueForKey:@“name”];

•Set object values: ■ [person setName:@“Pee-Wee Herman”]; ■ person.name = @“Pee-Wee Herman”; ■[person setValue:@“Pee-Wee Herman” forKey:@“name”];

12年12月23⽇日星期⽇日

Page 25: Network and Multitasking

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⽇日星期⽇日

Page 26: Network and Multitasking

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⽇日星期⽇日

Page 27: Network and Multitasking

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⽇日星期⽇日

Page 28: Network and Multitasking

Key-Value Observing (KVO)

•To listen for changes:

•To stop listening for changes: -(void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;

-(void)removeObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath;

12年12月23⽇日星期⽇日

Page 29: Network and Multitasking

Key-Value Observing (KVO) •Observing a value change: -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (context == myContext) { // Do something } else { // Don’t forget to call super } }

12年12月23⽇日星期⽇日

Page 30: Network and Multitasking

Demo

12年12月23⽇日星期⽇日

Page 31: Network and Multitasking

NSInvocationOperation

Concrete subclass of NSOperation

For lightweight tasks where creating a subclass is overkill- (void)someAction:(id)sender

{

NSInvocationOperation *operation =

[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doWork:)

object:someObject];

[queue addObject:operation];

[operation release];

}

12年12月23⽇日星期⽇日

Page 32: Network and Multitasking

Apple Push Notification Service

12年12月23⽇日星期⽇日

Page 33: Network and Multitasking

12年12月23⽇日星期⽇日

Page 34: Network and Multitasking

12年12月23⽇日星期⽇日

Page 35: Network and Multitasking

12年12月23⽇日星期⽇日

Page 36: Network and Multitasking

工作流

12年12月23⽇日星期⽇日

Page 37: Network and Multitasking

12年12月23⽇日星期⽇日

Page 38: Network and Multitasking

Block and GCD

12年12月23⽇日星期⽇日

Page 39: Network and Multitasking

Block定义

int (^oneFrom)(int); ! ! oneFrom = ^(int anInt) { ! ! return anInt - 1; ! }; ! ! NSLog(@"%d",oneFrom(10));

12年12月23⽇日星期⽇日

Page 40: Network and Multitasking

12年12月23⽇日星期⽇日

Page 41: Network and Multitasking

12年12月23⽇日星期⽇日

Page 42: Network and Multitasking

Writing to Local Variables

12年12月23⽇日星期⽇日

Page 43: Network and Multitasking

Writing to Local Variables

12年12月23⽇日星期⽇日

Page 44: Network and Multitasking

typedef void (^ScheduleFetcherResultBlock)(NSArray *classes, ! ! ! ! ! ! ! ! ! ! NSError *error);

- (void)fetchClassesWithBlock:(ScheduleFetcherResultBlock)theBlock;

12年12月23⽇日星期⽇日

Page 45: Network and Multitasking

- (void)fetchClassesWithBlock:(ScheduleFetcherResultBlock)theBlock { ! // Copy the block to ensure that it is not kept on the stack: ! resultBlock = [theBlock copy]; ! ! NSURL *xmlURL = [NSURL URLWithString: ! ! ! ! ! @"http://bignerdranch.com/xml/schedule"]; ! NSURLRequest *req = [NSURLRequest requestWithURL:xmlURL ! ! ! ! ! ! ! ! ! ! cachePolicy:NSURLRequestReturnCacheDataElseLoad ! ! ! ! ! ! ! ! ! timeoutInterval:30]; ! connection = [[NSURLConnection alloc] initWithRequest:req ! ! ! ! ! ! ! ! ! ! ! ! delegate:self]; ! if (connection) ! { ! ! responseData = [[NSMutableData alloc] init]; ! }resultBlock(nil, error);

}

12年12月23⽇日星期⽇日

Page 46: Network and Multitasking

12年12月23⽇日星期⽇日

Page 47: Network and Multitasking

12年12月23⽇日星期⽇日

Page 48: Network and Multitasking

12年12月23⽇日星期⽇日

Page 49: Network and Multitasking

UIViewAnimation style Animation

- (void)setSelectedVeg:(id)sender{        [selectedVegetableIcon setAlpha:0.0];! [UIView beginAnimations:@"setSelectedVeg" context:nil];! float angle = [self spinnerAngleForVegetable:sender];! [vegetableSpinner setTransform:CGAffineTransformMakeRotation(angle)];! [UIView setAnimationDuration:0.4];! [UIView setAnimationDelegate:self];! [UIView setAnimationDidStopSelector:@selector(done)];! [UIView commitAnimations];!}-(void)done{! [selectedVegetableIcon setAlpha:1.0];}

12年12月23⽇日星期⽇日

Page 50: Network and Multitasking

- (void)setSelectedVeg:(id)sender{        [selectedVegetableIcon setAlpha:0.0];        [UIView animateWithDuration:0.4            animations: ^{             float angle = [self spinnerAngleForVegetable:sender];             [vegetableSpinner setTransform:CGAffineTransformMakeRotation(angle)];            }             completion:^(BOOL finished) {               [selectedVegetableIcon setAlpha:1.0];    }];

}以上代码来⾃自WWDC2010 iPlant PlantCareViem.m

12年12月23⽇日星期⽇日

Page 51: Network and Multitasking

NSNotification ! void (^block)(NSNotification *); ! block=^(NSNotification *noti){ ! ! NSLog(@"%@",[noti object]); ! }; ! queue =[[NSOperationQueue alloc] init]; ! [[NSNotificationCenter defaultCenter] addObserverForName:@"Blocktest" ! ! ! ! ! ! ! ! ! ! ! ! ! object:self ! ! ! ! ! ! ! ! ! ! ! ! ! queue:queue ! ! ! ! ! ! ! ! ! ! ! ! usingBlock:block];

[[NSNotificationCenter defaultCenter] postNotificationName:@"Blocktest" object:self];

12年12月23⽇日星期⽇日

Page 52: Network and Multitasking

NSOperation

! void (^oneFrom)(void); ! ! oneFrom = ^(void) { ! ! NSLog(@"from opt"); ! }; ! NSOperation *opt=[[NSOperation alloc] init]; ! [opt setCompletionBlock:oneFrom]; ! [queue addOperation:opt];

12年12月23⽇日星期⽇日

Page 53: Network and Multitasking

[regex enumerateMatchesInString:src options:0 range:NSMakeRange(0, [src length]) ! ! usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { ! ! NSString*resultString = [src substringWithRange:[result range]];

NSRange range0= NSMakeRange(0,[resultString length]);NSRange range1= [[regex2 firstMatchInString:resultString options:0 range:range0] range];

! ! NSString*link=[resultString substringWithRange:range1]; ! ! ! ! ! ! ! ! }];

NSRegularExpression* regex2=nil;regex2 =[[NSRegularExpression alloc] initWithPattern:@"(?<=>).*?(?=</a>)" ! ! ! ! ! ! ! ! ! ! options:NSRegularExpressionCaseInsensitive error:nil];

正则匹配

12年12月23⽇日星期⽇日

Page 54: Network and Multitasking

GCD

Grand Central DIspatch

12年12月23⽇日星期⽇日

Page 55: Network and Multitasking

12年12月23⽇日星期⽇日

Page 56: Network and Multitasking

12年12月23⽇日星期⽇日

Page 57: Network and Multitasking

12年12月23⽇日星期⽇日

Page 58: Network and Multitasking

12年12月23⽇日星期⽇日

Page 59: Network and Multitasking

12年12月23⽇日星期⽇日

Page 60: Network and Multitasking

12年12月23⽇日星期⽇日

Page 61: Network and Multitasking

12年12月23⽇日星期⽇日

Page 62: Network and Multitasking

12年12月23⽇日星期⽇日

Page 63: Network and Multitasking

12年12月23⽇日星期⽇日

Page 64: Network and Multitasking

12年12月23⽇日星期⽇日

Page 65: Network and Multitasking

-(IBAction)extractCurAll:(id)sender{ ! [indicator setHidden:NO]; ! [indicator startAnimation:sender]; ! NSLog(@"extractCurAll"); ! ! ! dispatch_queue_t queue; ! queue = dispatch_queue_create("com.example.operation", NULL); ! dispatch_async(queue, ^{ ! ! // Create a CGPDFDocumentRef from the input PDF file. ! ! CGPDFDocumentRef pdfDoc = NULL; ! ! pdfDoc = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL); ! ! [[PDFImageExtrator sharedPDFImageExtrator] setUrl:pdfURL]; ! ! [[PDFImageExtrator sharedPDFImageExtrator] ExtratorWithPDF:pdfDoc]; ! ! dispatch_async(dispatch_get_main_queue(),^{ ! ! ! [indicator stopAnimation:sender]; ! ! ! [indicator setHidden:YES]; ! ! ! [openBtn setEnabled:YES]; ! ! }); ! }); ! dispatch_release(queue);!}

12年12月23⽇日星期⽇日

Page 66: Network and Multitasking

use block and GCD

-(void)blockwork{ dispatch_queue_t queue; ! queue = dispatch_queue_create("com.example.operation", NULL); ! dispatch_async(queue, ^{ ! ! // Create a CGPDFDocumentRef from the input PDF file. NSString *urlStr=@"http://www.apple.com/home/images/t_hero.png"; NSData *imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]]; UIImage *image=[UIImage imageWithData:imageData]; ! ! dispatch_async(dispatch_get_main_queue(),^{ ! ! ! self.imageView.image = image; ! ! }); ! }); ! dispatch_release(queue);!}

12年12月23⽇日星期⽇日

Page 67: Network and Multitasking

use GCD change our NSThread Code!

12年12月23⽇日星期⽇日

Page 68: Network and Multitasking

ResourceSession 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⽇日星期⽇日

Page 69: Network and Multitasking

Queuesdispatch_queue_t

dispatch_queue_createdispatch_queue_get_labeldispatch_get_main_queuedispatch_get_global_queuedispatch_get_current_queuedispatch_maindispatch_asyncdispatch_async_fdispatch_syncdispatch_sync_fdispatch_afterdispatch_after_fdispatch_applydispatch_apply_f

Timedispatch_time_t

dispatch_timedispatch_walltime

Oncedispatch_once_t

dispatch_oncedispatch_once_f

Sourcesdispatch_source_t

dispatch_source_createdispatch_source_canceldispatch_source_testcanceldispatch_source_merge_datadispatch_source_get_handledispatch_source_get_maskdispatch_source_get_datadispatch_source_set_timerdispatch_source_set_event_handlerdispatch_source_set_event_handler_fdispatch_source_set_cancel_handlerdispatch_source_set_cancel_handler_f

Objectsdispatch_object_t

dispatch_retaindispatch_releasedispatch_suspenddispatch_resumedispatch_debugdispatch_get_contextdispatch_set_contextdispatch_set_finalizer_fdispatch_set_target_queue

Groupsdispatch_group_t

dispatch_group_createdispatch_group_enterdispatch_group_leavedispatch_group_waitdispatch_group_notifydispatch_group_notify_fdispatch_group_asyncdispatch_group_async_f

Semaphoresdispatch_semaphore_t

dispatch_semaphore_createdispatch_semaphore_signaldispatch_semaphore_wait

Not Objects

6012年12月23⽇日星期⽇日

Page 70: Network and Multitasking

Q&A

12年12月23⽇日星期⽇日