Date post: | 06-May-2015 |
Category: |
Technology |
Upload: | kong-xianbo |
View: | 926 times |
Download: | 1 times |
Networking & Multitasking
孔祥波
12年12月23⽇日星期⽇日
network,tcp/ip,socket,CFNetWork
http, restful api
thread: posix thread, NSThread,NSOperation,push notification
Block and GCD
12年12月23⽇日星期⽇日
tcp/ip
20世纪六十年代 美国国防部
加州伯克利大学 BSD Unix
OSI 七层/TCP/IP四层模型
应用层http, pop3,smtp,ftp&
12年12月23⽇日星期⽇日
Socket
tcp/udp
tcp 三次握手
server/client 模型
server: open/bind/listen/connected/(send,recv)/close
client: open/bind/connect/(send,recv)/close
12年12月23⽇日星期⽇日
CFNetworkCFStream
RUNLoop base
CFReadStream create stream, set call back and runloop, call back read bytes
CFWriteStream
12年12月23⽇日星期⽇日
http
http protocol
Web service,SOAP,XML-RPC
Get RSS and ATOM feeds
download file
12年12月23⽇日星期⽇日
web service restful api
12年12月23⽇日星期⽇日
one more thing
12年12月23⽇日星期⽇日
debug network package
tcpdump -A -s0 -i en1 host hostnameand port 80
Wireshark network protocol dump
12年12月23⽇日星期⽇日
Multitasking
12年12月23⽇日星期⽇日
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⽇日星期⽇日
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⽇日星期⽇日
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⽇日星期⽇日
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⽇日星期⽇日
UIKit and Threads
Unless otherwise noted, UIKit classes are not threadsafe
Objects must be created and messaged from the main thread
12年12月23⽇日星期⽇日
debug
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
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⽇日星期⽇日
NSOperation
12年12月23⽇日星期⽇日
basic
Abstract superclass
Manages thread creation and lifecycle
Encapsulate a unit of work in an object
•Specify priorities and dependencies
12年12月23⽇日星期⽇日
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⽇日星期⽇日
KVC/KVO
12年12月23⽇日星期⽇日
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⽇日星期⽇日
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⽇日星期⽇日
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⽇日星期⽇日
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⽇日星期⽇日
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⽇日星期⽇日
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⽇日星期⽇日
Demo
12年12月23⽇日星期⽇日
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⽇日星期⽇日
Apple Push Notification Service
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
工作流
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
Block and GCD
12年12月23⽇日星期⽇日
Block定义
int (^oneFrom)(int); ! ! oneFrom = ^(int anInt) { ! ! return anInt - 1; ! }; ! ! NSLog(@"%d",oneFrom(10));
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
Writing to Local Variables
12年12月23⽇日星期⽇日
Writing to Local Variables
12年12月23⽇日星期⽇日
typedef void (^ScheduleFetcherResultBlock)(NSArray *classes, ! ! ! ! ! ! ! ! ! ! NSError *error);
- (void)fetchClassesWithBlock:(ScheduleFetcherResultBlock)theBlock;
12年12月23⽇日星期⽇日
- (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⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
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⽇日星期⽇日
- (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⽇日星期⽇日
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⽇日星期⽇日
NSOperation
! void (^oneFrom)(void); ! ! oneFrom = ^(void) { ! ! NSLog(@"from opt"); ! }; ! NSOperation *opt=[[NSOperation alloc] init]; ! [opt setCompletionBlock:oneFrom]; ! [queue addOperation:opt];
12年12月23⽇日星期⽇日
[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⽇日星期⽇日
GCD
Grand Central DIspatch
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
12年12月23⽇日星期⽇日
-(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⽇日星期⽇日
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⽇日星期⽇日
use GCD change our NSThread Code!
12年12月23⽇日星期⽇日
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⽇日星期⽇日
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⽇日星期⽇日
Q&A
12年12月23⽇日星期⽇日