ShayneChow +
微博 Github Twitter

iOS多线程 -- NSOperation(二)

本文将利用一个列表加载网络图片来展示一列App的下载量的示例来演示多线程下载多图片的应用。

本文以下示例中涉及UITableView的性能优化,多线程异步下载,线程阻塞等问题,最后会介绍如何使用第三方框架快速优雅地解决以上多线程下载网络图片的问题。

使用storyboard拖拽出一个UITableVIewController,选择系统自带subtitle的cell样式即可。接着倒入提前准备好的apps.plist资源文件(用于模型内容展示),之后开始创建UITableVIewController控制器并关联IB,并开始搭建App模型。

  1. // ZXApp.h
  2. #import <Foundation/Foundation.h>
  3. @interface ZXApp : NSObject
  4. /** 图标 */
  5. @property (nonatomic, copy) NSString *icon;
  6. /** 名称 */
  7. @property (nonatomic, copy) NSString *name;
  8. /** 下载数 */
  9. @property (nonatomic, copy) NSString *download;
  10. - (instancetype)initWithDict:(NSDictionary *)dict;
  11. + (instancetype)appWithDict:(NSDictionary *)dict;
  12. @end
  1. // ZXApp.m
  2. #import "ZXApp.h"
  3. @implementation ZXApp
  4. - (instancetype)initWithDict:(NSDictionary *)dict {
  5. if (self = [super init]) {
  6. [self setValuesForKeysWithDictionary:dict];
  7. }
  8. return self;
  9. }
  10. + (instancetype)appWithDict:(NSDictionary *)dict {
  11. return [[self alloc] initWithDict:dict];
  12. }
  13. @end

完成UITableViewController的基本设置,注意此时需要在storyboard中设置好cell的identifierID与数据源方法中设置的ID保持一致。

  1. // ZXTableViewController.m
  2. #import "ZXTableViewController.h"
  3. #import "ZXApp.h"
  4. @interface ZXTableViewController ()
  5. /** 需要展示的数据 */
  6. @property (nonatomic, strong) NSArray *apps;
  7. @end
  8. @implementation ZXTableViewController
  9. #pragma mark - lazy
  10. - (NSArray *)apps {
  11. if (!_apps) {
  12. NSString *path = [[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil];
  13. NSArray *tempArr = [NSArray arrayWithContentsOfFile:path];
  14. NSMutableArray *models = [NSMutableArray arrayWithCapacity:tempArr.count];
  15. for (NSDictionary *dict in tempArr) {
  16. ZXApp *app = [ZXApp appWithDict:dict];
  17. [models addObject:app];
  18. }
  19. _apps = [models copy];
  20. }
  21. return _apps;
  22. }
  23. #pragma mark - Table view data source
  24. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  25. return self.apps.count;
  26. }
  27. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  28. NSLog(@"%@", [NSThread currentThread]);
  29. // 1.创建cell
  30. static NSString *identifier = @"app";
  31. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
  32. // 2.设置数据
  33. ZXApp *app = self.apps[indexPath.row];
  34. cell.textLabel.text = app.name;
  35. cell.detailTextLabel.text = app.download;
  36. // 下载图片
  37. /*
  38. 存在的问题:
  39. 1.图片在主线程中下载, 阻塞主线程
  40. 2.重复下载, 浪费资源
  41. */
  42. NSURL *url = [NSURL URLWithString:app.icon];
  43. NSData *data = [NSData dataWithContentsOfURL:url];
  44. UIImage *image = [UIImage imageWithData:data];
  45. cell.imageView.image = image;
  46. // 3.返回cell
  47. return cell;
  48. }
  49. @end

要完成网络图片下载,使用NSOperation实现时会遇到以下两个问题:

  • 重复下载
  • 线程阻塞

下面就依次解决这2个问题。

用户在来回拖动TableView的时候,基于目前的程序每次出现cell都会去下载一次对应的图片,这就造成了程序的性能损耗。

那么怎么解决这个问题呢?这里就需要用到缓存了。

针对此程序有3种获取图片的方式:

1.直接下载 2.内存缓存 3.沙盒缓存

直接下载和内存缓存我们都很好理解,那么沙盒是个什么鬼呢?一般很少接触到,这里关于沙盒的详细问题就不做过多介绍,直接祭出神器,一个基于NSString的扩展分类专门用来处理沙盒存储路径的,以后需用到沙盒存储的地方可以直接拿来使用。

  1. // NSString+ZX.h
  2. #import <Foundation/Foundation.h>
  3. @interface NSString (ZX)
  4. /**
  5. * 生成缓存目录全路径
  6. */
  7. - (instancetype)cacheDir;
  8. /**
  9. * 生成文档目录全路径
  10. */
  11. - (instancetype)docDir;
  12. /**
  13. * 生成临时目录全路径
  14. */
  15. - (instancetype)tmpDir;
  16. @end
  1. // NSString+ZX.m
  2. #import "NSString+ZX.h"
  3. @implementation NSString (ZX)
  4. - (instancetype)cacheDir {
  5. NSString *dir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  6. return [dir stringByAppendingPathComponent:[self lastPathComponent]];
  7. }
  8. - (instancetype)docDir {
  9. NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
  10. return [dir stringByAppendingPathComponent:[self lastPathComponent]];
  11. }
  12. - (instancetype)tmpDir {
  13. NSString *dir = NSTemporaryDirectory();
  14. return [dir stringByAppendingPathComponent:[self lastPathComponent]];
  15. }
  16. @end

在TableView视图控制器中导入头文件,创建缓存属性,然后在cell的加载中加入缓存方法

  1. // ZXTableViewController.m 除以下方法外其他省略未写(未改动)
  2. #import "NSString+ZX.h"
  3. // 懒加载图片缓存属性
  4. - (NSMutableDictionary *)imageCaches {
  5. if (!_imageCaches) {
  6. _imageCaches = [NSMutableDictionary dictionary];
  7. }
  8. return _imageCaches;
  9. }
  10. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  11. NSLog(@"%@", [NSThread currentThread]);
  12. // 1.创建cell
  13. static NSString *identifier = @"app";
  14. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
  15. // 2.设置数据
  16. ZXApp *app = self.apps[indexPath.row];
  17. cell.textLabel.text = app.name;
  18. cell.detailTextLabel.text = app.download;
  19. // 下载图片
  20. /*
  21. 存在的问题:
  22. 1.图片在主线程中下载, 阻塞主线程
  23. 2.重复下载, 浪费资源
  24. */
  25. // 1.从字典冲获取需要展示图片
  26. UIImage *image = self.imageCaches[app.icon];
  27. if (image == nil) {
  28. // NSLog(@"下载图片");
  29. // 2.判断沙盒缓存中有没有
  30. NSData *data = [NSData dataWithContentsOfFile:[app.icon cacheDir]];
  31. if (data == nil) {
  32. NSLog(@"下载图片");
  33. // 需要下载
  34. NSURL *url = [NSURL URLWithString:app.icon];
  35. data = [NSData dataWithContentsOfURL:url];
  36. UIImage *image = [UIImage imageWithData:data];
  37. // 缓存下载好的数据到内存中
  38. self.imageCaches[app.icon] = image;
  39. // 缓存到沙盒
  40. [data writeToFile:[app.icon cacheDir] atomically:YES];
  41. // 更新UI
  42. cell.imageView.image = image;
  43. }else
  44. {
  45. NSLog(@"从沙盒加载图片");
  46. // 根据沙盒缓存创建图片
  47. UIImage *image = [UIImage imageWithData:data];
  48. // 进行内存缓存
  49. self.imageCaches[app.icon] = image;
  50. // 更新UI
  51. cell.imageView.image = image;
  52. }
  53. }else
  54. {
  55. NSLog(@"使用内存缓存");
  56. // 更新UI
  57. cell.imageView.image = image;
  58. }
  59. // 3.返回cell
  60. return cell;
  61. }

自此即可解决重复下载问题了。

重复下载顺利解决,但是第一次进入程序时,仍需要等待程序将图片下载完成才能显示界面,这个体验是非常不好的,而这就是耗时的下载操作在主线程阻塞了UI的加载导致的,所以接下来我们就来解决线程阻塞问题。

1、首先添加操作即队列属性

  1. /** 操作缓存 */
  2. @property (nonatomic, strong) NSMutableDictionary *operations;
  3. /** 队列 */
  4. @property (nonatomic, strong) NSOperationQueue *queue;

2、对相关属性的懒加载

  1. - (NSMutableDictionary *)operations {
  2. if (!_operations) {
  3. _operations = [NSMutableDictionary dictionary];
  4. }
  5. return _operations;
  6. }
  7. - (NSOperationQueue *)queue {
  8. if (!_queue) {
  9. _queue = [[NSOperationQueue alloc] init];
  10. }
  11. return _queue;
  12. }

3、更新数据源方法

  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  2. NSLog(@"%@", [NSThread currentThread]);
  3. // 1.创建cell
  4. static NSString *identifier = @"app";
  5. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
  6. // 2.设置数据
  7. ZXApp *app = self.apps[indexPath.row];
  8. cell.textLabel.text = app.name;
  9. cell.detailTextLabel.text = app.download;
  10. // 注意点: cell上面的图片, 默认是没有宽高的, 所以还未下载完时候显示不出来,这时需要添加一个占位图片
  11. cell.imageView.image = [UIImage imageNamed:@"占位图标"];
  12. // 下载图片
  13. /*
  14. 存在的问题:
  15. 1.图片在主线程中下载, 阻塞主线程
  16. 2.重复下载, 浪费资源
  17. */
  18. // 1.从字典冲获取需要展示图片
  19. UIImage *image = self.imageCaches[app.icon];
  20. if (image == nil) {
  21. // 2.从沙盒中获取图片
  22. __block NSData *data = [NSData dataWithContentsOfFile:[app.icon cacheDir]];
  23. // 判断沙盒缓存中有没有
  24. if (data == nil) {
  25. // NSLog(@"下载图片");
  26. // 3.判断当前是否有操作正在下载这张图片
  27. NSBlockOperation *op = self.operations[app.icon];
  28. if (op == nil) {
  29. // 没有操作正在下载
  30. /*
  31. 存在问题:
  32. 1.重复下
  33. 2.重复设置 : reloadRowsAtIndexPaths
  34. */
  35. op = [NSBlockOperation blockOperationWithBlock:^{
  36. [NSThread sleepForTimeInterval:1.0];
  37. // 需要下载
  38. NSURL *url = [NSURL URLWithString:app.icon];
  39. data = [NSData dataWithContentsOfURL:url];
  40. // 判断图片是否下载成功
  41. if (data == nil) {
  42. // 移除下载操作的缓存
  43. [self.operations removeObjectForKey:app.icon];
  44. return;
  45. }
  46. UIImage *image = [UIImage imageWithData:data];
  47. // 缓存下载好的数据到内存中
  48. self.imageCaches[app.icon] = image;
  49. // 缓存到沙盒
  50. [data writeToFile:[app.icon cacheDir] atomically:YES];
  51. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  52. // 更新UI
  53. // cell.imageView.image = image;
  54. [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  55. NSLog(@"更新UI %zd", indexPath.row);
  56. // 移除缓存的下载操作
  57. [self.operations removeObjectForKey:app.icon];
  58. }];
  59. }];
  60. // 缓存当前图片对应的下载操作
  61. self.operations[app.icon] = op;
  62. // 添加操作到队列中
  63. [self.queue addOperation:op];
  64. }
  65. }else {
  66. // NSLog(@"从沙盒加载图片");
  67. // 根据沙盒缓存创建图片
  68. UIImage *image = [UIImage imageWithData:data];
  69. // 进行内存缓存
  70. self.imageCaches[app.icon] = image;
  71. // 更新UI
  72. cell.imageView.image = image;
  73. }
  74. }else {
  75. // NSLog(@"使用内存缓存");
  76. // 更新UI
  77. cell.imageView.image = image;
  78. }
  79. // 3.返回cell
  80. return cell;
  81. }

基本框架与上面相同,不赘述。

导入SDWebImage框架,#import "SDWebImage/UIImageView+WebCache.h",只需简单几步完成上面所有操作:

  1. //
  2. // ViewController.m
  3. // SDWebImageDemo
  4. //
  5. // Created by Xiang on 15/8/14.
  6. // Copyright (c) 2015年 周想. All rights reserved.
  7. //
  8. #import "ViewController.h"
  9. #import "ZXApp.h"
  10. #import "SDWebImage/UIImageView+WebCache.h"
  11. @interface ViewController ()
  12. /** 需要展示的数据 */
  13. @property (nonatomic, strong) NSArray *apps;
  14. @end
  15. @implementation ViewController
  16. #pragma mark - 懒加载
  17. - (NSArray *)apps {
  18. if (!_apps) {
  19. NSString *path = [[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil];
  20. NSArray *tempArr = [NSArray arrayWithContentsOfFile:path];
  21. NSMutableArray *models = [NSMutableArray arrayWithCapacity:tempArr.count];
  22. for (NSDictionary *dict in tempArr) {
  23. ZXApp *app = [ZXApp appWithDict:dict];
  24. [models addObject:app];
  25. }
  26. _apps = [models copy];
  27. }
  28. return _apps;
  29. }
  30. #pragma mark- datasource
  31. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  32. return self.apps.count;
  33. }
  34. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  35. // 1.创建cell
  36. static NSString *identifier = @"app";
  37. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
  38. // 2.设置数据
  39. ZXApp *app = self.apps[indexPath.row];
  40. cell.textLabel.text = app.name;
  41. cell.detailTextLabel.text = app.download;
  42. [cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.icon] placeholderImage:[UIImage imageNamed:@"1"]];
  43. // 3.返回cell
  44. return cell;
  45. }
  46. @end

是不是很简单。

本文涉及代码在这里

0

Opinion

Blog

About