自从自己尝试了书写简易版的SDWebImage框架功能,到近日查看该源码, 感觉SD实现的思路和自己的简易版差不多(当然了,我在没看源码前稍稍了解了一下SD的大致)。
网上很多文章都说说了关于SDWebImage相关知识,在这里我就不介绍,而且感觉网上的介绍内容也挺详细妥当的,我就不再一一详说了,只是一些我自己发现的一些小问题。
1,NSData和NSUrlSession
我发现SD从网络加载图片使用的是NSUrlSession,而不是我NSData子线程异步加载图片,这样就解决了图片下载进度条的问题,而我使用NSData方法一直找不到进度条的解决方案,而且NSUrlSession利用block或者代理可以更加灵活地控制网络图片的加载。
2,SDWebImage对gif支持
我们可以看到UIImage+GIF源文件中, SD对gif的代码处理支持,如果我们使用正常的gif图片加载方式,我测试过UIImageView显示显示依旧是静止,而使用分类UIImage+GIF是可以动态的,SD做得工作就是不断循环取出每张image
for (size_t i = 0; i < count; i++) {
CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
if (!image) {
continue;
}
duration += [self sd_frameDurationAtIndex:i source:source];
[images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
CGImageRelease(image);
}
if (!duration) {
duration = (1.0f / 10.0f) * count;
}
animatedImage = [UIImage animatedImageWithImages:images duration:duration];
然后返回一个动画的image对象
3,收到内存警告,自动帮清除图片缓存
当接受到系统发处的UIApplicationDidReceiveMemoryWarningNotification通知的时候,SD会做出一连串的清理缓存工作
// Subscribe to app events
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(clearMemory)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(cleanDisk)
name:UIApplicationWillTerminateNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(backgroundCleanDisk)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
这样在某种程度上,程序员就无需关心图片的问题。
缓存的有效时间为一周
static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week
// PNG signature bytes and data (below)
PS: SDWebImage的知识点很多, 推荐大家可以研究看一遍
后来我发现了一个有意思的东西,就是AFnetworking也有类似的功能,但是好像大家都不常用AFNetworking来处理UIImageView吧,而且他们2个好像相互怼对方的感觉,哈哈
网友评论