加载网络图片可以说是网络应用中必备的。如果单纯的去下载图片,而不去做多线程、缓存等技术去优化,加载图片时的效果与用户体验就会很差。

一、自己实现加载图片的方法

tips:

*iOS中所有网络访问都是异步的.(自己开线程去下载) *普通为模型增加UIImage属性的方法做的是内存缓存(下次启动还需要从网络重新加载), 而要做本地缓存的话,还要自己手动存储网络上下载的图片. *为了加快访问, 还需要自己去弄缓存.(内存缓存或者本地缓存) *当图片没有下载完成时,还要设置占位图片。

以下代码用NSOperation开异步线程下载图片,当下载完成时替换占位图片。

01.//
02.//  XNViewController.m
03.//  加载网络图片, 普通的用NSOperation来做.
04.//
05.//  Created by neng on 14-7-7.
06.//  Copyright (c) 2014年 neng. All rights reserved.
07.//
08. 
09.#import "XNViewController.h"
10.#import "XNApp.h"
11. 
12.@interface XNViewController ()
13.@property (nonatomic, strong) NSArray *appList;
14.@property (nonatomic, strong) NSOperationQueue *queue;
15.@end
16. 
17.@implementation XNViewController
18.#pragma mark - 懒加载
19. 
20.- (NSOperationQueue *)queue {
21.if (!_queue) _queue = [[NSOperationQueue alloc] init];
22.return _queue;
23.}
24. 
25.//可抽取出来写到模型中
26.- (NSArray *)appList {
27.if (!_appList) {
28.//1.加载plist到数组中
29.NSURL *url = [[NSBundle mainBundle] URLForResource:@"apps.plist" withExtension:nil];
30.NSArray *array = [NSArray arrayWithContentsOfURL:url];
31.//2.遍历数组
32.NSMutableArray *arrayM = [NSMutableArray array];
33.[array enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
34.[arrayM addObject:[XNApp appWithDict:obj]];  //数组中存放的是字典, 转换为app对象后再添加到数组
35.}];
36._appList = [arrayM copy];
37.}
38.return _appList;
39.}
40. 
41.- (void)viewDidLoad {
42.[super viewDidLoad];
43. 
44.self.tableView.rowHeight = 88;
45. 
46.//    NSLog(@"appList-%@",_appList);
47.}
48. 
49.#pragma mark - 数据源方法
50.- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
51.return self.appList.count;
52.}
53. 
54.- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
55.static NSString *ID = @"Cell";
56.UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
57. 
58.//用模型来填充每个cell
59.XNApp *app = self.appList[indexPath.row];
60.cell.textLabel.text = app.name;  //设置文字
61. 
62.//设置图像: 模型中图像为nil时用默认图像,并下载图像. 否则用模型中的内存缓存图像.
63.if (!app.image) {
64.cell.imageView.image = [UIImage imageNamed:@"user_default"];
65. 
66.[self downloadImg:indexPath];
67.}
68.else {
69.//直接用模型中的内存缓存
70.cell.imageView.image = app.image;
71.}
72.//  NSLog(@"cell--%p", cell);
73. 
74.return cell;
75.}
76. 
77./**始终记住, 通过模型来修改显示. 而不要试图直接修改显示*/
78.- (void)downloadImg:(NSIndexPath *)indexPath {
79.XNApp *app  = self.appList[indexPath.row]; //取得改行对应的模型
80. 
81.[self.queue addOperationWithBlock: ^{
82.NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:app.icon]]; //得到图像数据
83.UIImage *image = [UIImage imageWithData:imgData];
84. 
85.//在主线程中更新UI
86.[[NSOperationQueue mainQueue] addOperationWithBlock: ^{
87.//通过修改模型, 来修改数据
88.app.image = image;
89.//刷新指定表格行
90.[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
91.}];
92.}];
93.}
94. 
95.@end

上述代码只是做了内存缓存,而每次重新进入应用时,还会从网上重新下载。如果要继续优化上面的代码,需要自己去实现本地缓存。

二、使用第三方框架SDWebImage。(非常优秀)

*特点 :依赖的库很少.功能全面。 *自动实现磁盘缓存: *缓存图片名字是以MD5进行加密的后的名字进行命名.(因为加密那堆字串是唯一的) *[imageViewsd_setImageWithURL:v.fullImageURL placeholderImage:[UIImage imageNamed:@”xxxxx”]]. *就一个方法就实现了多线程带缓冲等效果.(可用带参数的方法,具体可看头文件)
用SDWebImage修改上面的方法后的代码可简化为:

01.#pragma mark - 数据源方法
02.- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
03.return self.appList.count;
04.}
05. 
06.- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
07.static NSString *ID = @"Cell";
08.UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
09. 
10.//用模型来填充每个cell
11.XNApp *app = self.appList[indexPath.row];
12.cell.textLabel.text = app.name;  //设置文字
13. 
14.//  //设置图像: 模型中图像为nil时用默认图像,并下载图像. 否则用模型中的内存缓存图像.
15.//  if (!cell.imageView.image) {
16.//      cell.imageView.image = [UIImage imageNamed:@"user_default"];
17.//
18.//      [self downloadImg:indexPath];
19.//  }
20.//  else {
21.//      //直接用模型中的内存缓存
22.//      cell.imageView.image = app.image;
23.//  }
24. 
25. 
26.//使用SDWebImage来完成上面的功能. 针对ImageView.
27.//一句话, 自动实现了异步下载. 图片本地缓存. 网络下载. 自动设置占位符.
28.[cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.icon] placeholderImage:[UIImage imageNamed:@"user_default"]];
29. 
30. 
31.return cell;
32.}
33. 
34./**始终记住, 通过模型来修改显示. 而不要试图直接修改显示*/
35.//- (void)downloadImg:(NSIndexPath *)indexPath {
36.//  XNApp *app  = self.appList[indexPath.row]; //取得改行对应的模型
37.//
38.//  [self.queue addOperationWithBlock: ^{
39.//      NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:app.icon]]; //得到图像数据
40.//      UIImage *image = [UIImage imageWithData:imgData];
41.//
42.//      //在主线程中更新UI
43.//      [[NSOperationQueue mainQueue] addOperationWithBlock: ^{
44.//          //通过修改模型, 来修改数据
45.//          app.image = image;
46.//          //刷新指定表格行
47.//          [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
48.//      }];
49.//  }];
50.//}
51. 
52.@end

SDWebImage中的一些参数: *SDWebImageRetryFailed = 1<< 0, 默认选项,失败后重试 *SDWebImageLowPriority = 1<< 1, 使用低优先级 *SDWebImageCacheMemoryOnly = 1<< 2, 仅仅使用内存缓存 *SDWebImageProgressiveDownload = 1<< 3, 显示现在进度 *SDWebImageRefreshCached = 1<< 4, 刷新缓存 *SDWebImageContinueInBackground =1 << 5, 后台继续下载图像 *SDWebImageHandleCookies = 1<< 6, 处理Cookie *SDWebImageAllowInvalidSSLCertificates= 1 << 7, 允许无效的SSL验证 *SDWebImageHighPriority = 1<< 8, 高优先级 *SDWebImageDelayPlaceholder = 1<< 9 延迟显示占位图片

出处:http://blog.csdn.net/xn4545945

iOS网络加载图片缓存与SDWebImage的更多相关文章

  1. iOS网络加载图片缓存策略之ASIDownloadCache缓存优化

    iOS网络加载图片缓存策略之ASIDownloadCache缓存优化   在我们实际工程中,很多情况需要从网络上加载图片,然后将图片在imageview中显示出来,但每次都要从网络上请求,会严重影响用 ...

  2. LruCache:从网络加载图片缓存实例

    OOM异常 堆内存用于存储实例对象,当程序不断创建对象,并且对象都有引用指向,那么垃圾回收机制就不会清理这些对象,当对象多到挤满堆内存的上限后,就产生OOM异常.Android系统为每个应用程序使用的 ...

  3. 【转】Android循环滚动广告条的完美实现,封装方便,平滑过渡,从网络加载图片,点击广告进入对应网址

    Android循环滚动广告条的完美实现,封装方便,平滑过渡,从网络加载图片,点击广告进入对应网址 关注finddreams,一起分享,一起进步: http://blog.csdn.net/finddr ...

  4. swift 基础小结01 --delegate、Optional、GCD的使用、request请求、网络加载图片并保存到沙箱、闭包以及桥接

    本文主要记录swift中delegate的使用.“?!”Optional的概念.GCD的使用.request请求.网络加载图片并保存到沙箱.闭包以及桥接. 一.delegate的使用 swift中de ...

  5. android 网络加载图片,对图片资源进行优化,并且实现内存双缓存 + 磁盘缓存

    经常会用到 网络文件 比如查看大图片数据 资源优化的问题,当然用开源的项目  Android-Universal-Image-Loader  或者 ignition 都是个很好的选择. 在这里把原来 ...

  6. ios -网络加载json和本地加载json

    1网络加载json的时候,要在模型的实现文件里写: - (void)setValue:(id)value forKey:(NSString *)key { } 2本地加载json的时候,要在模型的实现 ...

  7. Glide加载图片缓存库出现——You cannot start a load for a destroyed activity

    请记住一句话:不要再非主线程里面使用Glide加载图片,如果真的使用了,请把context参数换成getApplicationContext.

  8. 关于ios异步加载图片的几个开源项目

    一.HjCache  原文:http://www.markj.net/hjcache-iphone-image-cache/ 获取 HJCache: HJCache is up on github h ...

  9. 使用自定义的item、Adapter和AsyncTask、第三方开源框架PullToRefresh联合使用实现自定义的下拉列表(从网络加载图片显示在item中的ImageView)

    AsyncTask使用方法详情:http://www.cnblogs.com/zzw1994/p/4959949.html 下拉开源框架PullToRefresh使用方法和下载详情:http://ww ...

随机推荐

  1. Python 装饰器(进阶篇)

    装饰器是什么呢? 我们先来打一个比方,我写了一个python的插件,提供给用户使用,但是在使用的过程中我添加了一些功能,可是又不希望用户改变调用的方式,那么该怎么办呢? 这个时候就用到了装饰器.装饰器 ...

  2. 将输出语句打印至tomcat日志文件中

    tomcat-9.0.0 将程序中            System.out.println("------------这是输出语句System.out.println()-------- ...

  3. [转载]mysql下载安装

    转自https://www.cnblogs.com/tyhj-zxp/p/6693046.html 下载 打开:https://www.mysql.com/downloads/ 1.点击该项:

  4. C#: Delegate and Event

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  5. python 9*9 乘法表

    row = 1 while row <= 9: col = 1 while col <= row: print('%d*%d=%d'%(col, row, row*col), end='\ ...

  6. 回溯算法——解决n皇后问题

    所谓回溯(backtracking)是通过系统地搜索求解问题的方法.这种方法适用于类似于八皇后这样的问题:求得问题的一个解比较困难,但是检查一个棋局是否构成解很容易. 不多说,放上n皇后的回溯问题代码 ...

  7. ashx误删后,未能创建类型

    描述 今天,因为临时有事儿,需要去一趟其他城市,项目比较赶.所以只能在车上继续敲代码,倒霉的触摸板让我误删一个ashx一般处理程序.好死不死的这个文件的代码还很长. 我的做法是[垃圾桶]→[还原]→V ...

  8. HDU 1422 重温世界杯 DP题

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1422 解题报告:DP题,要使旅行的城市最多,关键是要选出一个城市作为开始,以这个城市作为开始的城市时, ...

  9. 【leetcode 简单】 第七十三题 丑数

    编写一个程序判断给定的数是否为丑数. 丑数就是只包含质因数 2, 3, 5 的正整数. 示例 1: 输入: 6 输出: true 解释: 6 = 2 × 3 示例 2: 输入: 8 输出: true ...

  10. Java并发编程(2) AbstractQueuedSynchronizer的设计与实现

    一 前言 上一篇分析AQS的内部结构,其中有介绍AQS是什么,以及它的内部结构的组成,那么今天就来分析下前面说的内部结构在AQS中的具体作用(主要在具体实现中体现). 二 AQS的接口和简单示例 上篇 ...