美文网首页
线程间的通信

线程间的通信

作者: 小盒盒 | 来源:发表于2016-03-26 18:58 被阅读34次
    - (void)test
    {
        [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
            // 图片的网络路径
           NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images"];
            // 加载图片
            NSData *data = [NSData dataWithContentsOfURL:url];
            
            // 生成图片
            UIImage *image = [UIImage imageWithData:data];
            
            // 回到主线程
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                self.imageView.image = image;
            }];
        }];
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // 图片的网络路径
            NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"];
    
            // 加载图片
            NSData *data = [NSData dataWithContentsOfURL:url];
    
            // 生成图片
            UIImage *image = [UIImage imageWithData:data];
    
            // 回到主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                self.imageView.image = image;
            });
        });
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        [self performSelectorInBackground:@selector(download3) withObject:nil];
    - (void)download3
    {
        // 图片的网络路径
        NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"];
        
        // 加载图片
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        // 生成图片
        UIImage *image = [UIImage imageWithData:data];
        
        // 回到主线程,显示图片
        [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
    //    [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
    //    [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];
    }
    }
    
    

    相关文章

      网友评论

          本文标题:线程间的通信

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