美文网首页iOS寒哥管理的技术专题iOS开发技巧
初探在多线程中不执行Delegate方法

初探在多线程中不执行Delegate方法

作者: 星期五__ | 来源:发表于2015-10-19 18:13 被阅读1481次

    初次使用案例

    如果有人没有碰到类似问题,可以尝试看看。

        dispatch_queue_t queue =    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            NSString *urlString =@"http://dlsw.baidu.com/sw-search-sp/soft/9d/25765/sogou_mac_32c_V3.2.0.1437101586.dmg";
            NSString *encodeURLString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url = [NSURL URLWithString:encodeURLString];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
            self.connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
            });
    

    代码很简答,就是使用NSURLConnection下载一个dmg格式的大文件。不一样的是这次我们还顺带使用到了GCD。
    若看官们还不了解GCD,简书好多大神都写过相关介绍GCD的文章。
    下面继续贴出关于NSURLConnection的delegate方法。

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
    }
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
    }
    
    

    好了,万事具备,让我们愉快地在delegate方法中下一个断点来运行。
    很快我们就会发现这根本不会调用代理方法。

    开始思考

    其实思考的方向也很明确,既然是线程系的铃,我们不妨用其来解。
    我也就不卖关子,原因其实就是:线程在delegate方法回调之前就已经提前结束了。
    如果这原因让你傻眼了,别急,我来用一个简单的例子来说明。

    - (void)viewDidLoad {
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(methodOne) object:nil];
        [thread start];
        [self performSelector:@selector(methodTwo) onThread:thread withObject:nil waitUntilDone:NO];
        NSLog(@"开始");
    }
    
    - (void)methodOne {
        NSLog(@"HI~");
    }
    
    - (void)methodTwo {
        NSLog(@"Hello~");
    }
    

    Run!!!告诉你结果:
    2015-10-19 17:44:36.469 Collection[5597:373711] HI~
    2015-10-19 17:44:36.469 Collection[5597:373446] 开始

    像这类问题就是因为导致了线程在执行结束后销毁。因此没法快乐地说Hello~

    而这其中还涉及到一个东西:RunLoop。
    这里也不过多介绍,稍微简单地科普一下:

    此处输入图片的描述此处输入图片的描述
    1. 主线程默然是启动RunLoop的。
    2. 子线程刚创建的时候没有RunLoop,需要自己手动去添加。
    3. 主线程会在app结束后销毁RunLoop。子线程结束后销毁RunLoop。

    说到这里也顺带说一下,我们广泛使用的AFNetWorking,这个第三方网络请求框架会开启一个新线程来添加自己runloop事件。
    无论使用NSOperation+NSURLConnection并发模型或者&GCD的并发模型,NSURLConnection遇到的这种无法回调的问题。
    AFNetWorking是这样解决的,单独建立起一个global thread,内置runLoop,所有的connection都由这个runloop发起,回调也是它接收,不占用主线程,也不耗CPU资源。

     + (void)networkRequestThreadEntryPoint:(id)__unused object {
        @autoreleasepool {
            [[NSThread currentThread] setName:@"AFNetworking"];
            
            NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
            [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
            [runLoop run];
        }
    }
    
    + (NSThread *)networkRequestThread {
        static NSThread *_networkRequestThread = nil;
        static dispatch_once_t oncePredicate;
        dispatch_once(&oncePredicate, ^{
              _networkRequestThread =
              [[NSThread alloc] initWithTarget:self
                  selector:@selector(networkRequestThreadEntryPoint:)
                  object:nil];
              [_networkRequestThread start];
        });
        return _networkRequestThread;
    }
    

    动手解决

    既然不想让线程提前结束,通常我们会用以下方式来解决。

    1. 创建NSTimer,挂载事件源,强行不让线程提前结束,当然这种方法太Low,我选择无视。
    2. 向创建的RunLoop添加NSPort,让线程不会自己停下,然后添加判断,来推出循环。
      不多说,上代码。
       dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
       
       dispatch_async(queue, ^{
           NSString *urlString =@"http://dlsw.baidu.com/sw-search-sp/soft/9d/25765/sogou_mac_32c_V3.2.0.1437101586.dmg";
           NSString *encodeURLString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
           NSURL *url = [NSURL URLWithString:encodeURLString];
           NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
           self.connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
           if (self.connection) {
               NSPort* port = [NSPort port];
               NSRunLoop* rl = [NSRunLoop currentRunLoop]; // Get the runloop
               [rl addPort:port forMode:NSDefaultRunLoopMode];
               [self.connection scheduleInRunLoop:rl forMode:NSDefaultRunLoopMode];
           }
           
           while(!_isFinished) {
               [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
           }
           
       });
    

    由于本文介绍到了线程和RunLoop这两个开发大家乐于讨论的概念
    大家就自行查阅啦~~

    相关文章

      网友评论

      • ddaa8dae50b0:请求本身是异步的, 为什么要放线程里?

      本文标题:初探在多线程中不执行Delegate方法

      本文链接:https://www.haomeiwen.com/subject/tqbzcttx.html