簡體   English   中英

NSCache存儲UITableView的圖像

[英]NSCache to store images for 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返回對象(這是app委托的保留屬性),imageCache作為實例變量,頂部有兩個方法。

當我滾動時,我在控制台中看到@“它不為空”,但我沒有看到提取的圖像,而是默認的20x20用戶黑色圖像。 有沒有人有想法,為什么會這樣? 我究竟做錯了什么?

謝謝!

你的代碼遺漏了一些東西。 我無法在你的hangiesCommunicator上調用fetchAvatarForUser:completion:方法,你的tableView:cellForRowAtIndexPath:方法沒有返回單元格,所以我認為你發布的代碼不會干凈地編譯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM