多线程:下载图片(不用SDWebImage)

#import <Foundation/Foundation.h>

@interface NSString (Path)
- (NSString *)appendDocument;
- (NSString *)appendCache;
- (NSString *)appendTmp;

@end



#import "NSString+Path.h"

@implementation NSString (Path)
- (NSString *)appendDocument {
    NSString *root = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];

    return [root stringByAppendingPathComponent:[self lastPathComponent]];
}

- (NSString *)appendCache {
    NSString *root = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];

    return [root stringByAppendingPathComponent:[self lastPathComponent]];
}

- (NSString *)appendTmp {
    NSString *root = NSTemporaryDirectory();

    return [root stringByAppendingPathComponent:[self lastPathComponent]];
}
@end
#import "ViewController.h"
#import "AppInfo.h"
#import "AppInfoCell.h"
#import "NSString+Path.h"
#define CZWeakSelf __weak typeof(self) weakSelf = self;
@interface ViewController ()
@property (nonatomic, strong) NSArray *data;// 表格数据
@property (nonatomic, strong) NSOperationQueue *download;// 下载队列
@property (nonatomic, strong) NSMutableDictionary *operationCache;// 操作缓存池
@property (nonatomic, strong) NSMutableDictionary *imageCache;// 图片缓存池
@property (nonatomic, strong) NSMutableArray *blackList; // 黑名单

// 声明方法
// 方便自己
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

#pragma mark - tableview 代理 & 数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

/*
 如果是注册cell 类型的,直接使用 [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];就可以从缠在池中取出可用的cell.如果cell 为nil ,自动创建一个cell

 如果是在storyboard 中注册的cell ,使用[tableView dequeueReusableCellWithIdentifier:ID] 来从缓存中取cell,也不会为nil
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *ID = @"Cell";
    AppInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    //    if (cell == nil) {
    //
    //    }
    // 判断cell 是否为空
    //    NSLog(@"%@",cell);

    AppInfo *app = self.data[indexPath.row];

    cell.nameLabel.text = app.name;
    cell.downloadLabel.text = app.download;
    // 同步下载图片
    /*
     1. 阻塞主线程(很卡)
     2. 重复下载 (造成用户经济损失)

     */
    // 设置占位图
    cell.iconView.image = [UIImage imageNamed:@"user_default"];


    // 判断模型是否有图片 -- MVC 解决
    if ([self.imageCache objectForKey:app.icon] != nil) {
        cell.iconView.image = [self.imageCache objectForKey:app.icon];
        NSLog(@"从内存加载图片");
        return cell;
    }

    // 先判断内存有没有缓存,再判断沙盒有没有缓存
    NSString *path = [app.icon appendCache];

    // 读取数据
    NSData *data = [NSData dataWithContentsOfFile:path];
    // 判断data 是否有值
    if (data) {
        NSLog(@"沙盒缓存");
        // 转换成UIImage
        UIImage *image = [UIImage imageWithData:data];
        // 保存到内存缓存中
        [self.imageCache setObject:image forKey:app.icon];
        // 显示图片
        cell.iconView.image = image;

        return cell;
    }


    // 操作缓存池在下载完之后,就应该清除
    if ([self.operationCache objectForKey:app.icon]) {
        NSLog(@"图片正在下载");
        return cell;
    }

    // 判断图片路径有没有问题
    // containsObject 判断数组是否包含某个元素
    if ([self.blackList containsObject:app.icon]) {
        NSLog(@"黑名单不需要再去下载");
        // 如果包含了,已经存在黑名单,不需要再次下载
        return cell;
    }

    [self downloadImage:indexPath];
    return cell;
}

/*
 1. 封装 (定义新的方法)
 2. 复制主要的代码
 3. 补充参数
 4. 调用新的方法
 5. 测试
 6. 优化新的方法
 */
- (void)downloadImage:(NSIndexPath *)indexPath {

    // 取出对应的模型
    AppInfo *app = self.data[indexPath.row];
    CZWeakSelf
    // 使用block 要注意 循环引用
    // block 中使用属性 -> self.属性名
    // 只要 block 中出现 self 就应该检查
    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{

        // 加载图片
        NSURL *url = [NSURL URLWithString:app.icon];
        // 接收二进制数据
        NSData *data = [NSData dataWithContentsOfURL:url];

        [[NSOperationQueue mainQueue] addOperationWithBlock:^{

            // 图片下载完成了
            // 清除下载操作
            [weakSelf.operationCache removeObjectForKey:app.icon];
            UIImage *image = [UIImage imageWithData:data];
            // 转成图片
            if (image) {
                // 把图片保存到沙盒
                [data writeToFile:[app.icon appendCache] atomically:YES];
                // 把图片保存到缓存池中去
                [weakSelf.imageCache setObject:image forKey:app.icon];

                // 下载完图片,不需要直接设置image. reloadData
                // 去除了image跟cell 的关系
                [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
            }else {
                // 记录黑名单
                [self.blackList addObject:app.icon];
            }
        }];

    }];
    // 把操作缓存起来
    [self.operationCache setObject:op forKey:app.icon];

    // 把操作添加到下载队列
    [self.download addOperation:op];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%@",self.operationCache);
}


#pragma mark - 懒加载
- (NSArray *)data {
    if (_data == nil) {
        _data = [AppInfo appInfoList];
    }
    return _data;
}

- (NSOperationQueue *)download {
    if (_download == nil) {
        _download = [[NSOperationQueue alloc]init];
        // 设置最大并发
//        _download.maxConcurrentOperationCount = 6;
    }
    return _download;
}

- (NSMutableDictionary *)operationCache {
    if (_operationCache == nil) {
        _operationCache = [NSMutableDictionary dictionary];

    }
    return _operationCache;
}

-  (NSMutableDictionary *)imageCache {
    if (_imageCache == nil) {
        _imageCache = [NSMutableDictionary dictionary];
    }
    return _imageCache;
}

- (NSMutableArray *)blackList {
    if (_blackList == nil) {
        _blackList = [NSMutableArray array];
    }
    return _blackList;
}

- (void)dealloc {
    NSLog(@"走了");
}

// 内存警告的方法
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"内存警告");
    // 内存警告可能是内存过大,内存不够用,需要我们去清理一些内存出来
    // 图片不会错乱
    // 如果图片保存在模型中,清理内存很麻烦
    [self.imageCache removeAllObjects];

    // 如果设置了最大并发数才有作用 (准备执行)
    [self.download cancelAllOperations];

    // 清除操作缓存
    [self.operationCache removeAllObjects];
}



@end
#import <UIKit/UIKit.h>

@interface AppInfo : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, copy) NSString *download;
//@property (nonatomic, strong) UIImage *image;

+ (instancetype)appInfoWithDict:(NSDictionary *)dict;

+ (NSArray *)appInfoList;
@end




#import "AppInfo.h"

@implementation AppInfo
+ (instancetype)appInfoWithDict:(NSDictionary *)dict {
    AppInfo *app = [[self alloc]init];
    [app setValuesForKeysWithDictionary:dict];
    return app;
}

+ (NSArray *)appInfoList {
    // 文件路径
    NSString *path = [[NSBundle mainBundle]pathForResource:@"apps.plist" ofType:nil];

    // 读取文件数
    NSArray *data = [NSArray arrayWithContentsOfFile:path];

    NSMutableArray *appList = [NSMutableArray arrayWithCapacity:data.count];

    // 这个方法效率比较高
    [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 把字典转成模型
        AppInfo *app = [AppInfo appInfoWithDict:obj];

        [appList addObject:app];
    }];

    return appList.copy;

}
@end
#import <UIKit/UIKit.h>

@interface AppInfoCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *downloadLabel;

@end

#import "AppInfoCell.h"

@implementation AppInfoCell

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

// 点击cell 或者滚动tableView都会调用此方法。这个方法调用频率很高
// 不适合写一些逻辑性的代码,尽量少写代码在这里
//- (void)layoutSubviews {
//    [super layoutSubviews];
//    NSLog(@"%s",__FUNCTION__);
//}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值