0

我想将图像保存到 TableViewcontroller 的缓存中。我写了下面的代码,但是 cacheImage 总是为零。

@property (nonatomic,strong)NSCache *imageCache;
@synthesize imageCache;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.imageCache = [[NSCache alloc] init];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    cell.textLabel.text = [[tableData objectAtIndex:indexPath.row] valueForKey:@"name"];
    cell.textLabel.font = [UIFont fontWithName:@"BebasNeue" size:24];
    cell.textLabel.textColor = [UIColor whiteColor];

    UIImage *cachedImage = [imageCache objectForKey:@"indexObject"];

    if (cachedImage) {
          dispatch_async(dispatch_get_main_queue(), ^{
              cell.imageView.image = cachedImage;
                });
         }
    else {


    NSString *imageURLString=[[tableData objectAtIndex:indexPath.row] valueForKey:@"picture"];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:imageURLString];
        NSData *data = [[NSData alloc] initWithContentsOfURL:url];
        UIImage *tmpImage = [[UIImage alloc] initWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{
            UITableViewCell *newsCell = [self.grillMenuTable cellForRowAtIndexPath:indexPath];
            [imageCache setObject:tmpImage forKey:@"indexObject"];
            if (newsCell)
            {
                newsCell.imageView.image=tmpImage;
                [newsCell setNeedsLayout];
            }
        });


    });
    }
    return cell;
}

我按照乔的建议使用了以下代码,但仍然 cell.imageview.image 始终为零。

 NSString *imageURLString=[[tableData objectAtIndex:indexPath.row] valueForKey:@"picture"];
    [[DLImageLoader sharedInstance] loadImageFromUrl:imageURLString
                                           completed:^(NSError *error, UIImage *imgData) {
                                               cell.imageView.image = imgData;
                                               }];
4

2 回答 2

1

不要试图重新发明轮子。你应该使用外部库来做到这一点,有一些很好的例子。看看SDWebImage,它完全符合您的要求。

使用它,您可以忘记队列,手动缓存...只需导入标头:

#import <SDWebImage/UIImageView+WebCache.h>

并且,在您的tableView:cellForRowAtIndexPath:方法中,您可以将图像设置为库提供的UIImageViewwith setImageWithURL:(或其任何变体:使用占位符等)方法:

NSString* imageURL = [[tableData objectAtIndex:indexPath.row] valueForKey:@"picture"];
[cell.imageView setImageWithURL:[NSURL URLWithString:imageURL]];

就这样。图书馆会为您处理一切。如果您想以某种方式管理其背后的缓存并对其进行配置,则可以使用SDWebImageManager该类(更多信息在 GitHub 页面中)。

于 2014-05-18T17:22:19.353 回答
1

这是您可以遵循的教程。不使用任何第三方。 https://sweettutos.com/2015/12/31/swift-how-to-asynchronously-download-and-cache-images-without-relying-on-third-party-libraries/

于 2019-04-02T11:10:13.810 回答