我有一种异步下载图像的方法。如果图像与对象数组有关(我构建的应用程序中的常见用例),我想缓存它们。这个想法是,我传递了一个索引编号(基于我通过桌子的indexpath。浏览的桌子),然后将图像藏在静态的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输出来看到这一点。但是即使在我的插入后:atindex:呼叫, [imageCache count] 永远不要离开零。

这是我第一次涉足静态变量,所以我想我做错了什么。

(上述代码大量修剪只能显示发生的事情的主要内容,因此在您看它时牢记这一点。)

有帮助吗?

解决方案

您似乎永远不会初始化 imageCache 可能很幸运有价值 0. 。初始化最好在班级的初始化中进行,例如:

@implementation ImageDownloader
// ...
+(void)initialize {
    imageCache = [[NSMutableArray alloc] init];
}
// ...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top