画像を非同期にダウンロードする方法があります。画像がオブジェクトの配列に関連している場合 (私が構築しているアプリの一般的な使用例)、それらをキャッシュしたいと考えています。アイデアは、インデックス番号を渡し (途中で作成しているテーブルの 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]
ゼロのままになることはありません。
これは静的変数への私の最初の進出なので、何か間違ったことをしていると思います。
(上記のコードは、何が起こっているかの主要な部分だけを示すために大幅に削除されているため、それを見るときはそのことを念頭に置いてください。)