同様のオブジェクト間の通信の静的変数
-
04-10-2019 - |
質問
画像を非同期的にダウンロードする方法があります。画像がオブジェクトの配列(私が構築しているアプリの一般的なユースケース)に関連している場合、それらをキャッシュしたいと思います。アイデアは、インデックス番号を渡します(私が作成しているテーブルのlow.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]
ゼロを離れることはありません。
これは静的変数への最初の進出なので、何か間違ったことをしていると思います。
(上記のコードは、何が起こっているのかの主なことだけを示すために非常に剪定されているので、あなたがそれを見るときにそれを念頭に置いてください。)
解決
あなたは決して初期化しないようです imageCache
そして、おそらくそれが価値を持っていることで幸運になりました 0
. 。初期化は、クラスの初期化で最もよく行われます。
@implementation ImageDownloader
// ...
+(void)initialize {
imageCache = [[NSMutableArray alloc] init];
}
// ...
所属していません StackOverflow