【问题标题】:Ios table cell image download by NSURLConnection sendAsynchronousRequest causes crash on table cell delete通过 NSURLConnection sendAsynchronousRequest 下载 Ios 表格单元格图像导致表格单元格删除时崩溃
【发布时间】:2015-09-29 09:12:15
【问题描述】:

我正在调用一个块来下载表格单元格图像。

[self downloadImageWithURL:aa completionBlock:^(BOOL succeeded, UIImage *image) {
            if (succeeded) {

            cell.imageView.image = image;


            ((DatabaseHelper *) [upcoming objectAtIndex:indexPath.row]).image = image;
        }
        }];



- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void     (^)(BOOL succeeded, UIImage *image))completionBlock
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                           if ( !error )
                           {
                               UIImage *image = [[UIImage alloc] initWithData:data];
                               completionBlock(YES,image);
                           } else{
                               completionBlock(NO,nil);
                           }
                       }];
}

它工作得非常好......但问题是,一旦调用任何单元格,如果我在异步请求完成之前删除该单元格,应用程序就会崩溃。 那么当我删除单元格时,如何从 NSoperation 队列中删除调用。

【问题讨论】:

    标签: ios uitableview nsurlconnection objective-c-blocks


    【解决方案1】:

    因为我相信您的代码在这里崩溃:[upcoming objectAtIndex:indexPath.row]。一个快速的解决方法是检查您的阵列是否可用,如下所示:

    [self downloadImageWithURL:aa completionBlock:^(BOOL succeeded, UIImage *image) {
            if (succeeded && upcoming && [upcoming lenght] > indexPath.row) {
    
            cell.imageView.image = image;
    
    
            ((DatabaseHelper *) [upcoming objectAtIndex:indexPath.row]).image = image;
        }
        }];
    

    更简洁的解决方案是实现一个控制器,用于存储您的所有请求。当你有这个时,很容易取消它们。您不应该在 UITableViewControllerUITableViewCell 中执行此操作。

    【讨论】:

    • 好的。以防万一:我认为您在重新加载数据时可能会遇到时间问题,例如:您加载单元格 0 的图像,然后重新加载数据,单元格 0 有另一个没有图像的数据源。现在可能会因为加载时间过长而将“旧”图像附加到新单元格。
    • 是的...我现在有 dat 问题..所以我认为最好的解决方案是从 nsoperationqueue 中删除该操作..所以我现在正在了解这一点
    • 这将是一个解决方案。更快的方法是在(重新)附加图像之前检查图像的路径。您可以为此使用tag 字段。您也可以对您的对象进行子类化以在其中存储您需要的数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多