我有一个异步下载图像的方法。如果图像与对象数组相关(我正在构建的应用程序中的一个常见用例),我想缓存它们。这个想法是,我传入一个索引号(基于我正在制作的表的 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];
}
//build up the incoming data in self.activeDownload with calls to didReceiveData...
- (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: 调用之后,[imageCache count]
也永远不会留下零。
这是我第一次涉足静态变量,所以我认为我做错了什么。
(上面的代码被大量删减,只显示正在发生的事情的主要内容,所以在查看它时请记住这一点。)