我有一個視圖控制器與表視圖。在表格視圖的每個單元格中,我都有一張從網上獲取的圖像 - 但其中許多圖像具有相同的圖像。所以,我現在做的是將提取的圖像存儲在NSCache對象中。它發生是這樣的:NSCache存儲圖像的UITableView
- (void)fetchAvatarForUser:(NSString *)uid completion:(void (^)(BOOL))compBlock
{
if (!imageCache) {
imageCache = [[NSCache alloc] init];
}
if (!avatarsFetched) {
avatarsFetched = [[NSMutableArray alloc] initWithCapacity:0];
}
if ([avatarsFetched indexOfObject:uid] != NSNotFound) {
// its already being fetched
} else {
[avatarsFetched addObject:uid];
NSString *key = [NSString stringWithFormat:@"user%@",uid];
NSString *path = [NSString stringWithFormat:@"users/%@/avatar",uid];
[crudClient getPath:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@",[operation.response allHeaderFields]);
UIImage *resImage = [UIImage imageWithData:[operation responseData]];
[imageCache setObject:resImage forKey:key];
compBlock(YES);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Got error: %@", error);
compBlock(NO);
}];
}
}
- (UIImage *)getAvatarForUser:(NSString *)uid
{
NSString *key = [NSString stringWithFormat:@"user%@",uid];
NSLog(@"Image cache has: %@",[imageCache objectForKey:key]);
return [imageCache objectForKey:key];
}
imageCache是一個實例變量,也avatarsFetched,crudClient是AFHTTPClient對象。 和,在表視圖:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
PostCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[PostCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Post *curPost = [displayedPosts objectAtIndex:indexPath.section];
cell.nickname.text = [curPost nickname];
UIImage *avatarImage = [self.delegateRef.hangiesCommunicator getAvatarForUser:curPost.userID];
if (avatarImage) {
cell.avatar.image = avatarImage;
NSLog(@"Its not null");
} else {
cell.avatar.image = [UIImage imageNamed:@"20x20-user-black"];
}
}
self.delegateRef.hangiesCommunicator返回與imageCache作爲一個實例變量,和在頂部的兩個方法的對象(其是應用程序委託的一個保留的屬性)。
當我滾動時,我在控制檯中看到@「Its not null」,但我沒有看到提取的圖像,而是默認的20x20用戶黑色圖像。有沒有人有一個想法,爲什麼會發生這種情況?我究竟做錯了什麼?
謝謝!
好吧,這不是整個代碼,但無論如何,我發現了錯誤。這很傻。 NSCache的作品! –