2012-11-29 29 views
3

我有一个视图控制器与表视图。在表格视图的每个单元格中,我都有一张从网上获取的图像 - 但其中许多图像具有相同的图像。所以,我现在做的是将提取的图像存储在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用户黑色图像。有没有人有一个想法,为什么会发生这种情况?我究竟做错了什么?

谢谢!

回答

0

你的代码缺少一些东西。我看不到你曾经在你的hangiesCommunicator上调用过fetchAvatarForUser:completion:方法,而你的tableView:cellForRowAtIndexPath:方法没有返回这个单元格,所以我不认为你发布的代码会干净地编译。

+0

好吧,这不是整个代码,但无论如何,我发现了错误。这很傻。 NSCache的作品! –