سؤال

لدي طريقة تقوم بتنزيل الصور بشكل غير متزامن. إذا كانت الصور مرتبطة بمجموعة من الكائنات (حالة استخدام شائعة في التطبيق التي أقوم ببنائها) ، فأنا أريد ذاكرة التخزين المؤقت لها. الفكرة هي أنني أمرر في رقم فهرس (استنادًا إلى 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 الخاص بي. ولكن حتى بعد إدراجي: AtIndex: اتصل ، [imageCache count] لا تترك الصفر.

هذا هو أول غزو لي في متغيرات ثابتة ، لذلك أفترض أنني أفعل شيئًا خاطئًا.

(تم تقليم الكود أعلاه بشكل كبير لإظهار الشيء الرئيسي فقط لما يحدث ، لذلك ضع ذلك في الاعتبار وأنت تنظر إليه.)

هل كانت مفيدة؟

المحلول

يبدو أنك لا تهيئ imageCache وربما حالفه الحظ في الحصول على القيمة 0. من الأفضل القيام بالتهيئة في تهيئة الفصل ، على سبيل المثال:

@implementation ImageDownloader
// ...
+(void)initialize {
    imageCache = [[NSMutableArray alloc] init];
}
// ...
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top