一、YYLabel
学习 YYTextAsyncExample,YYLabel 异步绘制效率要比UILabel高许多。
简单看下YYLabel实现原理:
1. YYLabel 设置 textLayout 属性;
2. YYLabel - setTextLayout
a. 解析属性,
b. 调用[self.layer setNeedsDisplay];
3. YYAsyncLayer
a. display 被调用;
b. 通过 YLAsyncLayerDelegate 生成一个 YYAsyncLayerDisplayTask;
c. 分别调用 task.willDisplay, 线程异步调用 task.display, 主线程调用 task.didDisplay;
d. display 后,生成UIImage,设置到self.contents;
4. YYLabel
a. 实现 - (YYAsyncLayerDisplayTask*)newAsyncDisplayTask;
b. 分别实现willDisplay,display,didDisplay 三个block;
c. willDisplay 删除掉附加的view和layer;
d. display 调整位置绘制文本;
e. didDisplay layer添加动画;
二、YYAnimatedImageView
UITableViewCell 上添加 YYAnimatedImageView,实现异步加载,解码来提高效率。
1. setImageWithURL:placeholder:options:progress:transform:completion
该方法为UIImageView+YYWebImage里实现的方法
a. 生成 _YYWebImageSetter(对下载的简单封装),取消当前URL下载,生成新的sentinel;
b. 通过 YYImageCache 获取内存缓存,存在,设置image,返回;
c. 设置默认图片;
d. 通过 _YYWebImageSetter 提供的队列(串行)异步执行 setter 的 setOperationWithSentinel 方法;
2. _YYWebImageSetter - setOperationWithSentinel
a. 通过YYWebImageManager 创建一个 NSOperation;
b. 取消之前的 operation,生成新sentinel并返回;
c. 通过dispatch_semaphore_wait / signal 保证线程同步;
3. YYWebImageManager - requestImageWithURL
a. 生成NSMutalbeURLRequest,并以参数形式生成 YYWebImageOperation;
b. 如果有用户名,密码,operation 设置 credential;
c. 加入到 _queue 中;
4. YYWebImageOperation
a. start,在新线程上运行 _startOperation; 并通过 UIApplication beginBackgroundTaskWithExpirationHandler 在进入后台时,取消任务;
b. a中新线程的创建:
. NSThread initWithTarget:selector:object;
. _networkThreadMain: 中运行 runloop,设置addPort:[runLoop addPort:[NSMachPort port] forModel:NSDefaultRunLoopMode];
. 这个线程会一直存在,代码里并没有在任务完成后removePort;
c. _startOperation
. YYImageCache 中读取内存缓存,存在,结束,返回;本地读取,有,返回;
. 线程执行_startRequest;
d. _startRequest
. 通过 request 生成 NSURLConnection;
5. NSURLConnectionDelegate
执行顺序依次:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
获取到size,创建大小相同的data;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
append data;
如果有渐进显示标记,会把当前拿到的数据生成image,返回,用来显示当前拿到的数据;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
接收完成,生成UIImage,解码;
缓存,返回,设置image;
6. 其他
YYWebImageOperation 里用的递归锁;
加入了黑名单功能,如果设置IgnoreFailedURL标记,之前失败过的url不在重新下载;
三、YYCache
高效率,多功能,分析如下:
1. YYMemoryCache
a. 数据存储为_YYLinkMap;
b. 线程锁用的pthread_mutex_t;
c. 队列为串行队列;
e. 可设置costLimit,countLimit,ageLimit;
f. 监听消息:UIApplicationDidReceiveMemoryWarningNotification,UIApplicationDidEnterBackgroundNotification;收到消息后并且设置相关标记后,remove所有对象;
g. 设置了个5s定时器,检测cost、count、age,超过限制时,自动清理;
h. _YYLinkMap 使用Core Foundation, CFMutableDictionaryRef _dic,提高效率;
i. _YYLinkMap 包含 head,tail,结构为双向链表;
2. YYDiskCache
四、YYDispatchQueuePool