SlideShare a Scribd company logo
1 of 70
Download to read offline
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⽇日星期⽇日
CFNetwork
                 CFStream

                 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⽇日星期⽇日
正则匹配

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



    [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];
    !   ! !     !  !   !   !   !
    }];




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⽇日星期⽇日
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⽇日星期⽇日
Queues                Objects                           Sources
          dispatch_queue_t          dispatch_object_t                dispatch_source_t

   dispatch_queue_create        dispatch_retain             dispatch_source_create
   dispatch_queue_get_label     dispatch_release            dispatch_source_cancel
   dispatch_get_main_queue      dispatch_suspend            dispatch_source_testcancel
   dispatch_get_global_queue    dispatch_resume             dispatch_source_merge_data
   dispatch_get_current_queue   dispatch_debug              dispatch_source_get_handle
   dispatch_main                dispatch_get_context        dispatch_source_get_mask
   dispatch_async               dispatch_set_context        dispatch_source_get_data
   dispatch_async_f             dispatch_set_finalizer_f    dispatch_source_set_timer
   dispatch_sync                dispatch_set_target_queue   dispatch_source_set_event_handler
   dispatch_sync_f                                          dispatch_source_set_event_handler_f
   dispatch_after                                           dispatch_source_set_cancel_handler
   dispatch_after_f                                         dispatch_source_set_cancel_handler_f
   dispatch_apply
   dispatch_apply_f                     Groups
                                    dispatch_group_t

                                dispatch_group_create
                                                                     Not Objects
                                dispatch_group_enter
           Semaphores           dispatch_group_leave
        dispatch_semaphore_t    dispatch_group_wait              Time                Once
                                dispatch_group_notify        dispatch_time_t     dispatch_once_t
   dispatch_semaphore_create    dispatch_group_notify_f
   dispatch_semaphore_signal    dispatch_group_async        dispatch_time        dispatch_once
   dispatch_semaphore_wait      dispatch_group_async_f      dispatch_walltime    dispatch_once_f




12年12月23⽇日星期⽇日
Q&A




12年12月23⽇日星期⽇日

More Related Content

What's hot

Nosql及其主要产品简介
Nosql及其主要产品简介Nosql及其主要产品简介
Nosql及其主要产品简介振林 谭
 
twMVC#36C#的美麗與哀愁
twMVC#36C#的美麗與哀愁twMVC#36C#的美麗與哀愁
twMVC#36C#的美麗與哀愁twMVC
 
Concurrency model for mysql data processing@rubyconf.tw 2012
Concurrency model for mysql data processing@rubyconf.tw 2012Concurrency model for mysql data processing@rubyconf.tw 2012
Concurrency model for mysql data processing@rubyconf.tw 2012Mu-Fan Teng
 
03 Managing Memory with ARC
03 Managing Memory with ARC03 Managing Memory with ARC
03 Managing Memory with ARCTom Fan
 
炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹
炎炎夏日學 Android 課程 -  Part1: Kotlin 語法介紹炎炎夏日學 Android 課程 -  Part1: Kotlin 語法介紹
炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹Johnny Sung
 
180518 ntut js and node
180518 ntut js and node180518 ntut js and node
180518 ntut js and nodePeter Yi
 
17 Localization
17 Localization17 Localization
17 LocalizationTom Fan
 
合久必分,分久必合
合久必分,分久必合合久必分,分久必合
合久必分,分久必合Qiangning Hong
 
Java多线程:驾驭Synchronize的方法
Java多线程:驾驭Synchronize的方法Java多线程:驾驭Synchronize的方法
Java多线程:驾驭Synchronize的方法yiditushe
 
千呼萬喚始出來的 Java SE 7
千呼萬喚始出來的 Java SE 7千呼萬喚始出來的 Java SE 7
千呼萬喚始出來的 Java SE 7Justin Lin
 
iOS程序设计-数据持久化
iOS程序设计-数据持久化iOS程序设计-数据持久化
iOS程序设计-数据持久化qiyutan
 
D2_node在淘宝的应用实践_pdf版
D2_node在淘宝的应用实践_pdf版D2_node在淘宝的应用实践_pdf版
D2_node在淘宝的应用实践_pdf版Jackson Tian
 
JCConf2015: groovy to gradle
 JCConf2015: groovy to gradle JCConf2015: groovy to gradle
JCConf2015: groovy to gradleChing Yi Chan
 
OpenResty/Lua Practical Experience
OpenResty/Lua Practical ExperienceOpenResty/Lua Practical Experience
OpenResty/Lua Practical ExperienceHo Kim
 
Java多线程设计模式
Java多线程设计模式Java多线程设计模式
Java多线程设计模式Tony Deng
 
twMVC#43 C#10 新功能介紹
twMVC#43 C#10 新功能介紹twMVC#43 C#10 新功能介紹
twMVC#43 C#10 新功能介紹twMVC
 
分布式系统缓存设计
分布式系统缓存设计分布式系统缓存设计
分布式系统缓存设计zhujiadun
 
分布式系统缓存设计
分布式系统缓存设计分布式系统缓存设计
分布式系统缓存设计aleafs
 

What's hot (20)

Nosql及其主要产品简介
Nosql及其主要产品简介Nosql及其主要产品简介
Nosql及其主要产品简介
 
twMVC#36C#的美麗與哀愁
twMVC#36C#的美麗與哀愁twMVC#36C#的美麗與哀愁
twMVC#36C#的美麗與哀愁
 
Concurrency model for mysql data processing@rubyconf.tw 2012
Concurrency model for mysql data processing@rubyconf.tw 2012Concurrency model for mysql data processing@rubyconf.tw 2012
Concurrency model for mysql data processing@rubyconf.tw 2012
 
03 Managing Memory with ARC
03 Managing Memory with ARC03 Managing Memory with ARC
03 Managing Memory with ARC
 
炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹
炎炎夏日學 Android 課程 -  Part1: Kotlin 語法介紹炎炎夏日學 Android 課程 -  Part1: Kotlin 語法介紹
炎炎夏日學 Android 課程 - Part1: Kotlin 語法介紹
 
180518 ntut js and node
180518 ntut js and node180518 ntut js and node
180518 ntut js and node
 
17 Localization
17 Localization17 Localization
17 Localization
 
Node way
Node wayNode way
Node way
 
合久必分,分久必合
合久必分,分久必合合久必分,分久必合
合久必分,分久必合
 
Java多线程:驾驭Synchronize的方法
Java多线程:驾驭Synchronize的方法Java多线程:驾驭Synchronize的方法
Java多线程:驾驭Synchronize的方法
 
千呼萬喚始出來的 Java SE 7
千呼萬喚始出來的 Java SE 7千呼萬喚始出來的 Java SE 7
千呼萬喚始出來的 Java SE 7
 
iOS程序设计-数据持久化
iOS程序设计-数据持久化iOS程序设计-数据持久化
iOS程序设计-数据持久化
 
D2_node在淘宝的应用实践_pdf版
D2_node在淘宝的应用实践_pdf版D2_node在淘宝的应用实践_pdf版
D2_node在淘宝的应用实践_pdf版
 
JCConf2015: groovy to gradle
 JCConf2015: groovy to gradle JCConf2015: groovy to gradle
JCConf2015: groovy to gradle
 
OpenResty/Lua Practical Experience
OpenResty/Lua Practical ExperienceOpenResty/Lua Practical Experience
OpenResty/Lua Practical Experience
 
Java多线程设计模式
Java多线程设计模式Java多线程设计模式
Java多线程设计模式
 
twMVC#43 C#10 新功能介紹
twMVC#43 C#10 新功能介紹twMVC#43 C#10 新功能介紹
twMVC#43 C#10 新功能介紹
 
Docker實務
Docker實務Docker實務
Docker實務
 
分布式系统缓存设计
分布式系统缓存设计分布式系统缓存设计
分布式系统缓存设计
 
分布式系统缓存设计
分布式系统缓存设计分布式系统缓存设计
分布式系统缓存设计
 

Similar to Network and Multitasking

iOs app 101
iOs app 101iOs app 101
iOs app 101Tom Sun
 
Huangjing renren
Huangjing renrenHuangjing renren
Huangjing renrend0nn9n
 
in in der 響應式編程
in in der 響應式編程in in der 響應式編程
in in der 響應式編程景隆 張
 
探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG
探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG
探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUGYingSiang Geng
 
Objc under the_hood_2013
Objc under the_hood_2013Objc under the_hood_2013
Objc under the_hood_2013Michael Pan
 
使用Javascript及HTML5打造協同運作系統
使用Javascript及HTML5打造協同運作系統使用Javascript及HTML5打造協同運作系統
使用Javascript及HTML5打造協同運作系統Hsu Ping Feng
 
Continuous Delivery Workshop with Ansible x GitLab CI (2nd)
Continuous Delivery Workshop with Ansible x GitLab CI (2nd)Continuous Delivery Workshop with Ansible x GitLab CI (2nd)
Continuous Delivery Workshop with Ansible x GitLab CI (2nd)Chu-Siang Lai
 
人人网技术架构的演进
人人网技术架构的演进人人网技术架构的演进
人人网技术架构的演进Laobiao Li
 
Node js实践
Node js实践Node js实践
Node js实践myzykj
 
twMVC#44 讓我們用 k6 來進行壓測吧
twMVC#44 讓我們用 k6 來進行壓測吧twMVC#44 讓我們用 k6 來進行壓測吧
twMVC#44 讓我們用 k6 來進行壓測吧twMVC
 
NoSQL-MongoDB介紹
NoSQL-MongoDB介紹NoSQL-MongoDB介紹
NoSQL-MongoDB介紹國昭 張
 
Ria的强力后盾:rest+海量存储
Ria的强力后盾:rest+海量存储 Ria的强力后盾:rest+海量存储
Ria的强力后盾:rest+海量存储 zhen chen
 
Ejb工作原理学习笔记
Ejb工作原理学习笔记Ejb工作原理学习笔记
Ejb工作原理学习笔记yiditushe
 
Node.js在淘宝的应用实践
Node.js在淘宝的应用实践Node.js在淘宝的应用实践
Node.js在淘宝的应用实践taobao.com
 
Class 20170126
Class 20170126Class 20170126
Class 20170126Ivan Wei
 

Similar to Network and Multitasking (20)

iOs app 101
iOs app 101iOs app 101
iOs app 101
 
Huangjing renren
Huangjing renrenHuangjing renren
Huangjing renren
 
in in der 響應式編程
in in der 響應式編程in in der 響應式編程
in in der 響應式編程
 
探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG
探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG
探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG
 
Objc under the_hood_2013
Objc under the_hood_2013Objc under the_hood_2013
Objc under the_hood_2013
 
Html 5 native drag
Html 5 native dragHtml 5 native drag
Html 5 native drag
 
使用Javascript及HTML5打造協同運作系統
使用Javascript及HTML5打造協同運作系統使用Javascript及HTML5打造協同運作系統
使用Javascript及HTML5打造協同運作系統
 
Mvc
MvcMvc
Mvc
 
Continuous Delivery Workshop with Ansible x GitLab CI (2nd)
Continuous Delivery Workshop with Ansible x GitLab CI (2nd)Continuous Delivery Workshop with Ansible x GitLab CI (2nd)
Continuous Delivery Workshop with Ansible x GitLab CI (2nd)
 
Glider
GliderGlider
Glider
 
人人网技术架构的演进
人人网技术架构的演进人人网技术架构的演进
人人网技术架构的演进
 
Node js实践
Node js实践Node js实践
Node js实践
 
twMVC#44 讓我們用 k6 來進行壓測吧
twMVC#44 讓我們用 k6 來進行壓測吧twMVC#44 讓我們用 k6 來進行壓測吧
twMVC#44 讓我們用 k6 來進行壓測吧
 
CRUD 綜合運用
CRUD 綜合運用CRUD 綜合運用
CRUD 綜合運用
 
NoSQL-MongoDB介紹
NoSQL-MongoDB介紹NoSQL-MongoDB介紹
NoSQL-MongoDB介紹
 
Ria的强力后盾:rest+海量存储
Ria的强力后盾:rest+海量存储 Ria的强力后盾:rest+海量存储
Ria的强力后盾:rest+海量存储
 
Ejb工作原理学习笔记
Ejb工作原理学习笔记Ejb工作原理学习笔记
Ejb工作原理学习笔记
 
Tcfsh bootcamp day2
 Tcfsh bootcamp day2 Tcfsh bootcamp day2
Tcfsh bootcamp day2
 
Node.js在淘宝的应用实践
Node.js在淘宝的应用实践Node.js在淘宝的应用实践
Node.js在淘宝的应用实践
 
Class 20170126
Class 20170126Class 20170126
Class 20170126
 

Network and Multitasking

  • 1. Networking & Multitasking 孔祥波 12年12月23⽇日星期⽇日
  • 2. network,tcp/ip,socket,CFNetWork http, restful api thread: posix thread, NSThread,NSOperation,push notification Block and GCD 12年12月23⽇日星期⽇日
  • 3. tcp/ip 20世纪六十年代 美国国防部 加州伯克利大学 BSD Unix OSI 七层/TCP/IP四层模型 应用层http, pop3,smtp,ftp& 12年12月23⽇日星期⽇日
  • 4. Socket tcp/udp tcp 三次握手 server/client 模型 server: open/bind/listen/connected/ (send,recv)/close client: open/bind/connect/(send,recv)/ close 12年12月23⽇日星期⽇日
  • 5. CFNetwork CFStream RUNLoop base CFReadStream create stream, set call back and runloop, call back read bytes CFWriteStream 12年12月23⽇日星期⽇日
  • 6. http http protocol Web service,SOAP,XML-RPC Get RSS and ATOM feeds download file 12年12月23⽇日星期⽇日
  • 7. web service restful api 12年12月23⽇日星期⽇日
  • 9. debug network package tcpdump -A -s0 -i en1 host hostnameand port 80 Wireshark network protocol dump 12年12月23⽇日星期⽇日
  • 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⽇日星期⽇日
  • 19. 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⽇日星期⽇日
  • 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⽇日星期⽇日
  • 24. 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⽇日星期⽇日
  • 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⽇日星期⽇日
  • 28. 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⽇日星期⽇日
  • 29. 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⽇日星期⽇日
  • 31. 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⽇日星期⽇日
  • 32. Apple Push Notification Service 12年12月23⽇日星期⽇日
  • 39. Block定义 int (^oneFrom)(int); ! ! oneFrom = ^(int anInt) { ! ! return anInt - 1; ! }; ! ! NSLog(@"%d",oneFrom(10)); 12年12月23⽇日星期⽇日
  • 42. Writing to Local Variables 12年12月23⽇日星期⽇日
  • 43. Writing to Local Variables 12年12月23⽇日星期⽇日
  • 44. typedef void (^ScheduleFetcherResultBlock)(NSArray *classes, ! ! ! ! ! ! ! ! ! ! NSError *error); - (void)fetchClassesWithBlock: (ScheduleFetcherResultBlock)theBlock; 12年12月23⽇日星期⽇日
  • 45. - (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⽇日星期⽇日
  • 49. 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⽇日星期⽇日
  • 50. - (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⽇日星期⽇日
  • 51. 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⽇日星期⽇日
  • 52. NSOperation ! void (^oneFrom)(void); ! ! oneFrom = ^(void) { ! ! NSLog(@"from opt"); ! }; ! NSOperation *opt=[[NSOperation alloc] init]; ! [opt setCompletionBlock:oneFrom]; ! [queue addOperation:opt]; 12年12月23⽇日星期⽇日
  • 53. 正则匹配 NSRegularExpression* regex2=nil; regex2 =[[NSRegularExpression alloc] initWithPattern:@"(?<=>).*?(?=</a>)" ! ! ! ! ! ! ! ! ! ! options:NSRegularExpressionCaseInsensitive error:nil]; [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]; ! ! ! ! ! ! ! ! }]; 12年12月23⽇日星期⽇日
  • 54. GCD Grand Central DIspatch 12年12月23⽇日星期⽇日
  • 65. -(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⽇日星期⽇日
  • 66. 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⽇日星期⽇日
  • 67. use GCD change our NSThread Code! 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⽇日星期⽇日
  • 69. Queues Objects Sources dispatch_queue_t dispatch_object_t dispatch_source_t dispatch_queue_create dispatch_retain dispatch_source_create dispatch_queue_get_label dispatch_release dispatch_source_cancel dispatch_get_main_queue dispatch_suspend dispatch_source_testcancel dispatch_get_global_queue dispatch_resume dispatch_source_merge_data dispatch_get_current_queue dispatch_debug dispatch_source_get_handle dispatch_main dispatch_get_context dispatch_source_get_mask dispatch_async dispatch_set_context dispatch_source_get_data dispatch_async_f dispatch_set_finalizer_f dispatch_source_set_timer dispatch_sync dispatch_set_target_queue dispatch_source_set_event_handler dispatch_sync_f dispatch_source_set_event_handler_f dispatch_after dispatch_source_set_cancel_handler dispatch_after_f dispatch_source_set_cancel_handler_f dispatch_apply dispatch_apply_f Groups dispatch_group_t dispatch_group_create Not Objects dispatch_group_enter Semaphores dispatch_group_leave dispatch_semaphore_t dispatch_group_wait Time Once dispatch_group_notify dispatch_time_t dispatch_once_t dispatch_semaphore_create dispatch_group_notify_f dispatch_semaphore_signal dispatch_group_async dispatch_time dispatch_once dispatch_semaphore_wait dispatch_group_async_f dispatch_walltime dispatch_once_f 12年12月23⽇日星期⽇日