2012-11-29 4 views
3

테이블보기가있는보기 컨트롤러가 있습니다. 테이블보기의 각 셀에, 그물에서 가져온 이미지가 -하지만 그들 중 많은 동일한 이미지가 있습니다. 그래서, 현재 내가하고있는 일은 가져온 이미지를 NSCache 객체에 저장하는 것입니다. 그것은 이런 식으로 발생합니다UITableView 용 이미지를 저장할 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 및 상단의 두 가지 방법으로 (앱 델리게이트의 유지 특성 인) 객체를 반환한다.

스크롤 할 때 콘솔에 @ "해당 없음"이 표시되지만 가져온 이미지는 보이지 않지만 기본 20x20 사용자 검정 이미지는 표시됩니다. 아무도 아이디어가 없나요? 왜 이런 일이 일어나고있는 걸까요? 내가 도대체 ​​뭘 잘못하고있는 겁니까?

감사합니다.

답변

0

코드에 누락 된 항목이 있습니다. hangiesCommunicator 및 tableView : cellForRowAtIndexPath : 메서드에서 셀을 반환하지 않으므로 게시 한 코드가 제대로 컴파일되지 않을 것이라고 생각합니다. fetchAvatarForUser : completion : 메서드를 호출 한 위치를 볼 수 없습니다.

+0

그래, 전체 코드가 아니지만 어쨌든 나는 버그를 발견했다. 바보 같아. NSCache 작품! –

관련 문제