gpt4 book ai didi

ios - 缓存 URL 图片 iphone UITableview

转载 作者:技术小花猫 更新时间:2023-10-29 10:40:54 24 4
gpt4 key购买 nike

我正在寻找有关如何将从 url 加载的图像缓存到 uitableview 的单元格中的教程。

我在这里找到了一个例子

http://www.ericd.net/2009/05/iphone-caching-images-in-memory.html#top

但是代码不完整。我是一个客观的 c 新手,所以我发现很难填补缺失的部分。

最佳答案

这是一个使用 NSCache 的简单 ImageCache 实现。 ImageCache 是一个单体。

ImageCache.h

    #import <Foundation/Foundation.h>

@interface ImageCache : NSObject

@property (nonatomic, retain) NSCache *imgCache;


#pragma mark - Methods

+ (ImageCache*)sharedImageCache;
//- (void) AddImage:(NSString *)imageURL: (UIImage *)image;
- (void) AddImage:(NSString *)imageURL withImage:(UIImage *)image;
- (UIImage*) GetImage:(NSString *)imageURL;
- (BOOL) DoesExist:(NSString *)imageURL;

@end

ImageCache.m

  #import "ImageCache.h"

@implementation ImageCache

@synthesize imgCache;

#pragma mark - Methods

static ImageCache* sharedImageCache = nil;

+(ImageCache*)sharedImageCache
{
@synchronized([ImageCache class])
{
if (!sharedImageCache)
sharedImageCache= [[self alloc] init];

return sharedImageCache;
}

return nil;
}

+(id)alloc
{
@synchronized([ImageCache class])
{
NSAssert(sharedImageCache == nil, @"Attempted to allocate a second instance of a singleton.");
sharedImageCache = [super alloc];

return sharedImageCache;
}

return nil;
}

-(id)init
{
self = [super init];
if (self != nil)
{
imgCache = [[NSCache alloc] init];
}

return self;
}

// - (void) AddImage:(NSString *)imageURL: (UIImage *)image
- (void) AddImage:(NSString *)imageURL withImage:(UIImage *)image
{
[imgCache setObject:image forKey:imageURL];
}

- (NSString*) GetImage:(NSString *)imageURL
{
return [imgCache objectForKey:imageURL];
}

- (BOOL) DoesExist:(NSString *)imageURL
{
if ([imgCache objectForKey:imageURL] == nil)
{
return false;
}

return true;
}


@end

示例

UIImage *image;

// 1. Check the image cache to see if the image already exists. If so, then use it. If not, then download it.

if ([[ImageCache sharedImageCache] DoesExist:imgUrl] == true)
{
image = [[ImageCache sharedImageCache] GetImage:imgUrl];
}
else
{
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: imgUrl]];
image = [[UIImage alloc] initWithData:imageData];

// Add the image to the cache
//[[ImageCache sharedImageCache] AddImage:imgUrl :image];

[[ImageCache sharedImageCache] AddImage:imgUrl withImage:image];
}

关于ios - 缓存 URL 图片 iphone UITableview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2265137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com