SDWebImage使用汇总

2017年2月10日
1.如何保存缓存图片
用如下方法,可能会不成功
原因:对象消失,无法进入block块进行存储。

+ (void)setNurseDefualtImage
{
    NSString *fieldId = [[NSUserDefaults standardUserDefaults]objectForKey:@"nurseId_image"];

    NSString *key = [NSString stringWithFormat:@"%@%@",[QNInfo sharedQNInfo].QNImageUrl ? [QNInfo sharedQNInfo].QNImageUrl : quanQuanImageUrl, fieldId];
    //不能用局部变量,对象会变成nil,直接return导致下面block接口没有进去
    UIImageView *headPortraitImage = [[UIImageView alloc]init];
    [headPortraitImage sd_setImageWithURL:[NSURL URLWithString:key] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

        NSString *nurseId = [[NSUserDefaults standardUserDefaults]objectForKey:@"nurseId"];
        NSString *key = [NSString stringWithFormat:@"%@_head",nurseId];

        if(image){
            [[SDImageCache sharedImageCache] removeImageForKey:key];
            [[SDImageCache sharedImageCache] storeImage:image forKey:key];
            [[SDImageCache sharedImageCache] defaultCachePathForKey:key];
        }
    }];
}

解决:改成用如下成员变量就可以(最好在朱页面创建的时候使用,不然页面销毁太快,对象变空后,就无法进入block了)

#import "MainViewController.h"
#import "UIImageView+WebCache.h"
@interface  MainViewController ()
{
     UIImageView *headPortraitImage;//用来下载默认图片用
}
@end
@implementation loginViewController
- (void)viewDidLoad
{
      headPortraitImage = [[UIImageView alloc] init];
}
- (void)setNurseDefualtImage
{
    NSString *fieldId = [[NSUserDefaults standardUserDefaults]objectForKey:@"nurseId_image"];

    NSString *key = [NSString stringWithFormat:@"%@%@",[QNInfo sharedQNInfo].QNImageUrl ? [QNInfo sharedQNInfo].QNImageUrl : quanQuanImageUrl, fieldId];
    [headPortraitImage sd_setImageWithURL:[NSURL URLWithString:key] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

        NSString *nurseId = [[NSUserDefaults standardUserDefaults]objectForKey:@"nurseId"];
        NSString *key = [NSString stringWithFormat:@"%@_head",nurseId];

        if(image){
            [[SDImageCache sharedImageCache] removeImageForKey:key];
            [[SDImageCache sharedImageCache] storeImage:image forKey:key];
            [[SDImageCache sharedImageCache] defaultCachePathForKey:key];
        }
    }];
}

- (void)loginBtnClick:(UIButton *)btn
{
      //请求默认护士头像图片
      [self setNurseDefualtImage];
}

@end

如果您发现本文对你有所帮助,如果您认为其他人也可能受益,请把它分享出去。

你可能感兴趣的:(SDWebImage使用汇总)