我有一个异步下载图像的方法。如果这些图像与一组对象相关(我正在构建的应用程序中的一个常见用例),我想缓存它们。我的想法是,我传入一个索引号(基于我正在生成的表的indexPath.row),然后将图像存储在一个静态的nsmutableArray中,该数组的键控在我正在处理的表的行上。
因此:
@implementation ImageDownloader
...
@synthesize cacheIndex;
static NSMutableArray *imageCache;
-(void)startDownloadWithImageView:(UIImageView *)imageView andImageURL:(NSURL *)url withCacheIndex:(NSInteger)index
{
self.theImageView = imageView;
self.cacheIndex = index;
NSLog(@"Called to download %@ for imageview %@", url, self.theImageView);
if ([imageCache objectAtIndex:index]) {
NSLog(@"We have this image cached--using that instead");
self.theImageView.image = [imageCache objectAtIndex:index];
return;
}
self.activeDownload = [NSMutableData data];
NSURLConnection *conn = [[NSURLConnection alloc]
initWithRequest:[NSURLRequest requestWithURL:url] delegate:self];
self.imageConnection = conn;
[conn release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Finished downloading.");
UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
self.theImageView.image = image;
NSLog(@"Caching %@ for %d", self.theImageView.image, self.cacheIndex);
[imageCache insertObject:image atIndex:self.cacheIndex];
NSLog(@"Cache now has %d items", [imageCache count]);
[image release];
}
我的索引通过了,我可以通过我的nslog输出看到。但即使在我的insertObject:atindex:call之后,
[imageCache count]
从不离开零。
这是我第一次研究静态变量,所以我假设我做错了什么。
(上面的代码经过了大量的删减,只显示了正在发生的事情的主要内容,所以当您查看时请记住这一点。)