多线程:使用ImageView分类下载图片(模仿 SDWebImage)

#import <UIKit/UIKit.h>

@interface UIImageView (WebImage)
- (void)setImageWithURLString:(NSString *)URLString;
@end


#import "UIImageView+WebImage.h"
#import <objc/runtime.h>
#import "DownLoadImageManager.h"

@interface UIImageView ()
@property (nonatomic, copy) NSString *currentURL;
@end

@implementation UIImageView (WebImage)
- (void)setImageWithURLString:(NSString *)URLString {

    // 分类不能直接添加属性 -> 如果能添加属性,用分类下载图片就完成了
    /*
     运行时(Runtime)来动态添加属性

     会没有用过(了解过)运行时机制 -> 第三方
     什么是运行时? OC是运行时做的

     运行时通常我们会用到三个: 
     1. 动态添加属性 -> 分类 (BlockKit)
     2. 交换方法地址 -> 安全上(怎么让数组越界而程序不崩,字典)
     3. 获取属性列表 -> 字典转模型 

     */
    // 下载图片
    self.image = nil;
    // 判断要下载的URL跟上一个下载的URL的关系
    if (![URLString isEqualToString:self.currentURL] && self.currentURL) {
        // 取消上一个下载操作
        [[DownLoadImageManager shareManager]cancelDownload:self.currentURL];
    }

    self.currentURL = URLString;

    [[DownLoadImageManager shareManager]downloadOperationWithURLString:self.currentURL finish:^(UIImage *image) {
        self.image = image;
    }];
}

#define CZCurrentURL "currentURL"
- (NSString *)currentURL {

//    @selector(currentURL) void * 相当于 oc 的 ID
    return objc_getAssociatedObject(self, CZCurrentURL);
}

- (void)setCurrentURL:(NSString *)currentURL {
    /*
     1. 绑定的对象
     2. 相当于属性名字 selector
     3. 属性的值
     4. 修饰方式

     OBJC_ASSOCIATION_ASSIGN = 0, assign
    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, retain(strong) nonatomic

    OBJC_ASSOCIATION_COPY_NONATOMIC = 3, copy nonatomic

     OBJC_ASSOCIATION_RETAIN = 01401, retain(strong) atomic
    OBJC_ASSOCIATION_COPY = 01403     copy atomic

     */
    // 动态绑定值到对象上
    objc_setAssociatedObject(self, CZCurrentURL, currentURL, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值