Pregunta

Tengo un método que descarga de forma asincrónica imágenes. Si las imágenes están relacionadas con una gran variedad de objetos (un caso de uso común en la aplicación que estoy construyendo), quiero almacenar en caché ellos. La idea es, paso en un número de índice (basado en el indexPath.row de la mesa que estoy haciendo por paso a través), y esconder la imagen estática en un NSMutableArray, introducido en la fila de la tabla que estoy tratando con.

de esta manera:

@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];

}

Mi índice está llegando bien, puedo ver que mi salida NSLog. Pero incluso después de mi InsertObject: atIndex: llamada, [imageCache count] nunca sale de cero

.

Esta es mi primera incursión en las variables estáticas, así que supongo que estoy haciendo algo mal.

(El código anterior está muy podada para mostrar sólo es lo principal de lo que está pasando, así que tener en cuenta como se mire.)

¿Fue útil?

Solución

Parece que no inicializar el imageCache y probablemente tuvo suerte con ello tener la 0 valor. La inicialización mejor se llevaría a cabo en la clase inicialización, por ejemplo:.

@implementation ImageDownloader
// ...
+(void)initialize {
    imageCache = [[NSMutableArray alloc] init];
}
// ...
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top