NSCache的使用,SDWebImage的使用,Reachability联网状态检测框架的使用

本文深入探讨了NSCache的高效缓存管理及其实现方式,同时展示了如何利用SDWebImage进行图片缓存,并通过Reachability框架实时检测网络状态,提供流畅的用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Reachability(联网状态的检测)框架的使用:
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;
    }
}













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值