美文网首页
iOS开发中NSOperation线程间通信?下载图片?

iOS开发中NSOperation线程间通信?下载图片?

作者: 随心吧 | 来源:发表于2017-02-22 15:46 被阅读78次
『导言』

iOS开发中如何用NSOperation进行快速的下载图片,并且图片显示?其中子线程主线程如何通信?

一、步骤:
1.建立队列Queue
2.封装操作NSBlockOperation
  2.1 dataWithContentsOfURL下载数据
  2.2 addOperation方法从子线程进入主线程
3.将操作Operation添加到队列Queue
二、代码:
   // 1 开子线程
    NSOperationQueue *queue =[[NSOperationQueue alloc] init];
    
    //2.封装操作
    NSBlockOperation *op1 =[NSBlockOperation blockOperationWithBlock:^{
        //2.1下载图片
        NSURL *url = [NSURL URLWithString:@"http://f.hiphotos.baidu.com/image/pic/item/1f178a82b9014a90330244a7a1773912b31beee8.jpg"];
        
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image =[UIImage imageWithData:data];
        NSLog(@"Download ----%@",[NSThread currentThread]);

        
        //2.2更新UI;进入主线程Main
        
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            self.iconImageView.image = image;
            NSLog(@"UI ----%@",[NSThread currentThread]);
            
        }];
        
    }];

    //3  添加操作到队列
    [queue addOperation:op1];
三、分析:
  • 打印结果:
   /*  打印结果:
     
     2017-02-22 15:29:29.334 11-掌握-NSOperation线程间通信[1040:50068] Download ----<NSThread: 0x608000267f80>{number = 4, name = (null)}
     2017-02-22 15:29:29.335 11-掌握-NSOperation线程间通信[1040:49699] UI ----<NSThread: 0x608000076e80>{number = 1, name = main}
     */
  • 分析结果
1.number!=1 ,下载图片在子线程
2.number = 1,更新UI图片显示在主线程Main

相关文章

网友评论

      本文标题:iOS开发中NSOperation线程间通信?下载图片?

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