网络图片处理过程中怎么解决一个相同的网络地址重复请求的问题

多少年了 都在换汤不换的问SDWebImage的实现原理

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,strong)UITableView * tableView;
@property(nonatomic,strong)NSOperationQueue * queue;
/**key_URL地址 value_UIImage*/
@property(nonatomic,strong)NSMutableDictionary * images;
/**key_URL地址 value_操作*/
@property(nonatomic,strong)NSMutableDictionary * operations;
@property(nonatomic,strong)NSDictionary * dict;
@end
static NSString * cellID = @"cellID";
@implementation ViewController
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
        _tableView.dataSource = self;
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.queue = [[NSOperationQueue alloc]init];
    self.images = [NSMutableDictionary dictionary];
    self.operations = [NSMutableDictionary dictionary];
    self.dict = [NSDictionary dictionary];
    [self.view addSubview:self.tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 13;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
    UIImage * image = self.images[@"http:666.png"];
   
    if (image == nil ) {//没有图片
        NSOperation * operation = self.operations[@"http:666.png"];
        if (operation == nil) {//下载
            operation = [NSBlockOperation blockOperationWithBlock:^{
                NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http:666.png"]];
                UIImage * downloadImage = [UIImage imageWithData:data];
                self.images[@"http:666.png"] = downloadImage;
                [self.operations removeObjectForKey:@"http:666.png"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    cell.imageView.image = downloadImage;
                });
            }];
            [self.queue addOperation:operation];
            self.operations[@"http:666.png"] = operation;
        }else{//正在下载
            cell.imageView.image = [UIImage imageNamed:@"占位图"];
        }
        
    }else{//已经有图片
        cell.imageView.image = image;
    }
    
    
    
    
    return cell;
}
@end

未完待续

你可能感兴趣的:(网络图片处理过程中怎么解决一个相同的网络地址重复请求的问题)