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

时间:2010-05-24 18:44:24

标签: iphone objective-c static-variables

我有一种异步下载图像的方法。如果图像与一个对象数组相关(我正在构建的应用程序中常见的用例),我想缓存它们。我的想法是,我传入一个索引号(基于我正在制作的表的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 个答案:

答案 0 :(得分:1)

你似乎永远不会初始化imageCache,并且可能幸运的是它具有值0。初始化最好在类初始化中完成,例如:

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