iOS使用RAC在UITableViewCell中加载图像

时间:2014-03-27 19:44:43

标签: ios asynchronous uitableview uiimage reactive-cocoa

刚开始使用RAC,我想知道如何在TableView中的单元格中异步加载图像。 我正在尝试使用文档中的示例,但说实话,我并不是那么理解...... 问题是该项目是用RAC编写的,所以我想做正确的事情。

我尝试了什么?:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"tableCell";
  CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  cell.elementName.text = self.myListOfElements[indexPath.row].elementName;
  RAC(cell.imageView, image) = [[finalImage map:^(NSURL *url) {
                                  return  [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.myListOfElements[indexPath.row].url]]];
                                    }] deliverOn:RACScheduler.mainThreadScheduler];
}

但这不起作用...... 有人知道用RAC做这件事的正确方法吗?

2 个答案:

答案 0 :(得分:0)

我从未使用过RAC,但根据示例,您看起来引用了一个您似乎没有的URL。

RAC(self.imageView, image) = 
[
    [
        [
            [
                client fetchUserWithUsername:@"joshaber"
            ]
            deliverOn:[RACScheduler scheduler]
        ]
        map:^(User *user) {
            // Download the avatar (this is done on a background queue).
            return [[NSImage alloc] initWithContentsOfURL:user.avatarURL];
        }
    ]
    // Now the assignment will be done on the main thread.
    deliverOn:RACScheduler.mainThreadScheduler
];

在本节的示例中:

[
    [
        client fetchUserWithUsername:@"joshaber"
    ]
    deliverOn:[RACScheduler scheduler]
]

-fetchUserWithUsername是返回包含用于下载图像的URL的User对象的函数。

答案 1 :(得分:0)

此行假设已在CustomTableViewCell的imageView属性中创建并设置了UIImageView对象:

  RAC(cell.imageView, image) = [[finalImage map:^(NSURL *url) {

据推测,这个UIImageView对象是在CustomTableViewCell类的初始化程序或-prepareForReuse方法中创建的。如果不是,那可能是你问题的一部分。

请注意,此代码看起来并不安全。如果重新使用CustomTableViewCell实例 ,那么您可能会第二次在对象上调用RAC(cell.imageView, image),这将是一个问题。 (另一方面,如果-prepareForReuse每次创建一个新的UIImageView,那么这不应该是一个问题。)