NSCache 是苹果官方提供的缓存类,用法与 NSMutableDictionary 的用法很相似,在 AFNetworking 和 SDWebImage 中,使用它来管理缓存
NSCache 是线程安全的,在多线程操作中,不需要对 Cache 加锁
NSCache 的 Key 只是做强引用,不需要实现 NSCopying 协议
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SDWebImage框架的使用:(做图片缓存就一句话搞定)
<span style="font-size:18px;">[cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.icon] placeholderImage:[UIImage imageNamed:@"user_default"]];
</span>
还可以显示下载进度:
<span style="font-size:18px;">[cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.icon] placeholderImage:[UIImage imageNamed:@"user_default"] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
// receivedSize 已经接受到的大小
// expectedSize 期望的大小,总大小
float progress = (float)receivedSize/expectedSize;
NSLog(@"下载进度 %f", progress);
} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
NSLog(@"%@", [NSThread currentThread]);
}];
</span>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
typedef enum : NSInteger {
NotReachable = 0, // 没有连接
ReachableViaWiFi, // wifi
ReachableViaWWAN // 2G/3G/4G
} NetworkStatus;
#import "ViewController.h"
#import "Reachability.h"
@interface ViewController ()
@property(nonatomic,strong)Reachability *reach;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 判断能否连接到某一个主机
// http://www.baidu.com
self.reach = [Reachability reachabilityWithHostName:@"baidu.com"];
// 添加通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged) name:kReachabilityChangedNotification object:nil];
// 开始监听
[self.reach startNotifier];
}
- (void)dealloc
{
// 停止监听
[self.reach stopNotifier];
// 移除监听 // 移除整个控制器里所有的监听
// [[NSNotificationCenter defaultCenter] removeObserver:self];
// 移除控制器里的kReachabilityChangedNotification监听
[[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}
- (void)reachabilityChanged
{
// 状态
switch (self.reach.currentReachabilityStatus) {
case NotReachable:
NSLog(@"没有连接");
break;
case ReachableViaWiFi:
NSLog(@"不用花钱");
break;
case ReachableViaWWAN:
NSLog(@"要流量");
break;
default:
NSLog(@"。。。。。。");
break;
}
}