我有一个带有表视图的视图控制器。在表格视图的每个单元格中,我有一个从网络中获取的图像 - 但是其中许多图像具有相同的图像。所以,我目前正在做的是将获取的图像存储在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返回对象(这是app委托的保留属性),其中imageCache作为实例变量,顶部有两个方法。
当我滚动时,我在控制台中看到@“它不为空”但我没有看到提取的图像,而是默认的20x20用户黑色图像。有没有人有想法,为什么会这样?我做错了什么?
谢谢!
答案 0 :(得分:0)
你的代码遗漏了一些东西。我无法在你的hangiesCommunicator上看到你调用fetchAvatarForUser:completion:方法的地方你的tableView:cellForRowAtIndexPath:方法没有返回单元格,所以我不认为你发布的代码会干净地编译。 / p>