代码之家  ›  专栏  ›  技术社区  ›  Dan Ray

用于类类型对象之间通信的静态变量

  •  0
  • Dan Ray  · 技术社区  · 15 年前

    我有一个异步下载图像的方法。如果这些图像与一组对象相关(我正在构建的应用程序中的一个常见用例),我想缓存它们。我的想法是,我传入一个索引号(基于我正在生成的表的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:call之后, [imageCache count] 从不离开零。

    这是我第一次研究静态变量,所以我假设我做错了什么。

    (上面的代码经过了大量的删减,只显示了正在发生的事情的主要内容,所以当您查看时请记住这一点。)

    1 回复  |  直到 15 年前
        1
  •  1
  •   Georg Fritzsche    15 年前

    您似乎从未初始化 imageCache 很可能是因为它有价值 0 . 初始化最好在类的初始化中完成,例如:

    @implementation ImageDownloader
    // ...
    +(void)initialize {
        imageCache = [[NSMutableArray alloc] init];
    }
    // ...
    
    推荐文章