我有一个带有表格视图的视图控制器。在表格视图的每个单元格中,我都有一个从网上获取的图像 - 但其中许多具有相同的图像。所以,我目前正在做的是将获取的图像存储在 NSCache 对象中。它是这样发生的:
- (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-user-black 图像。有人知道吗,为什么会这样?我究竟做错了什么?
谢谢!