0
我有一種異步下載圖像的方法。如果圖像與一組對象(我正在構建的應用程序中的一個常見用例)相關,我想緩存它們。我的想法是,我傳入一個索引號(基於我通過的表的indexPath.row),然後將圖像存儲在一個靜態NSMutableArray中,該靜態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]
也不會留下零。
這是我第一次進入靜態變量,所以我認爲我做錯了什麼。
(上面的代碼被大量刪減,只顯示這是怎麼回事的主要的東西,所以記住這一點,你看看吧。)
呵呵。我有點想知道初始化它。在' - (ImageDownloader *)init'中執行它顯然是錯誤的。沒有跨過我的腦海有一個CLASS初始值設定項。這可能現在正在工作,除了我現在(正確地說,我想)在我第一次去if([imageCache objectAtIndex:index]){')時會出現超出範圍的錯誤。當我們在這裏時,你如何有條件地測試Obj-C中的數組索引? – 2010-05-24 18:59:27
'if(index <[imageCache count])' – 2010-05-24 19:18:47