介绍
这篇文章给大家介绍如何在IOS中加载大量的网络图片,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
<强> 1,概述强>
在IOS下通过URL读一张网络图片并不像其他编程语言那样可以直接把图片路径放到图片路径的位置就好,而是需要我们通过一段类似流的方式去加载网络图片,接着才能把图片放入图片路径显示。比如:
- - - - - - (UIImage *), getImageFromURL: (NSString *) fileURL { ,//NSLog (@"执行图片下载函数“),,, ,UIImage *,结果,,, ,NSData *, data =, (NSData dataWithContentsOfURL: [NSURL URLWithString: fileURL]];=,result [UIImage imageWithData:数据];,, ,return 结果; }
加载网络图片可以说是网络应用中必备的。如果单纯的去下载图片,而不去做多线程,缓存等技术去优化,加载图片时的效果与用户体验就会很差。
优化思路为:
(1)本地缓存
(2)异步加载
(3)加载完毕前使用占位图片
<强> 2,优化方法强>
方法1:用NSOperation开异步线程下载图片,当下载完成时替换占位图片
# import “XNViewController.h" # import “XNApp.h" @interface XNViewController () @property (原子,,强烈),NSArray * appList; @property (原子,,强烈),NSOperationQueue *队列; @end @implementation XNViewController # pragma mark 安康;懒加载 安康;(NSOperationQueue *) queue { ,if (! _queue), _queue =, [[NSOperationQueue alloc], init); ,return _queue; }//可抽取出来写到模型中 安康;(NSArray *) appList { ,if (! _appList), {//1。加载plist到数组中 ,NSURL * url =, [[NSBundle mainBundle], URLForResource: @" apps.plist", withExtension: nil); ,NSArray * array =, (NSArray arrayWithContentsOfURL: url);//2。遍历数组 ,NSMutableArray * arrayM =, (NSMutableArray 数组); ,[array enumerateObjectsUsingBlock: ^ (id obj, NSUInteger idx,, BOOL *停止),{ ,,(arrayM addObject: [XNApp appWithDict: obj]];,//数组中存放的是字典,,转换为应用程序对象后再添加到数组 ,}];=,_appList [arrayM 副本); ,} ,return _appList; } 安康;(空白)viewDidLoad { ,[super viewDidLoad];=,self.tableView.rowHeight 88;//,,NSLog (@" appList - % @" _appList); } # pragma mark 安康;数据源方法 安康;(NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection:也(NSInteger) section { ,return self.appList.count; } 安康;(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath { ,static NSString * ID =, @" Cell"; ,UITableViewCell * cell =, (tableView dequeueReusableCellWithIdentifier: ID); ,//用模型来填充每个细胞 ,XNApp * app =, self.appList (indexpath。row);=,,cell.textLabel.text  app.name;,//设置文字 ,//设置图像:,模型中图像为nil时用默认图像,并下载图像只否则用模型中的内存缓存图像。 ,if (! app.image), {=,cell.imageView.image [UIImage imageNamed: @" user_default"]; ,[self downloadImg indexPath):; ,} ,else { ,//直接用模型中的内存缓存=,,cell.imageView.image  app.image; ,}//,NSLog (@"细胞——% p",,细胞); ,return 细胞; }/* *始终记住,,通过模型来修改显示只而不要试图直接修改显示*/安康;(空白)downloadImg:(NSIndexPath *) indexPath { ,XNApp * app =, self.appList [indexpath。row];,//取得改行对应的模型 ,[self.queue addOperationWithBlock: ^ { ,,NSData * imgData =, (NSData dataWithContentsOfURL: [NSURL URLWithString: app.icon]];,//得到图像数据 ,,UIImage * image =, [UIImage imageWithData imgData):; ,,//在主线程中更新UI ,,[[NSOperationQueue mainQueue], addOperationWithBlock:, ^ { ,,,,//通过修改模型,,来修改数据 ,,,,app.image =,形象; ,,,,//刷新指定表格行 ,,,,(self.tableView reloadRowsAtIndexPaths: @ [indexPath], withRowAnimation: UITableViewRowAnimationNone); ,}]; ,}]; } @end如何在IOS中加载大量的网络图片