Ios 重构uitableviewcell异步图像加载

Ios 重构uitableviewcell异步图像加载,ios,uitableview,grand-central-dispatch,Ios,Uitableview,Grand Central Dispatch,所以我有个问题……对我来说,在CellForRowatineXpath方法中使用dispatch\u异步代码对我来说太笨重和混乱了 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { static NSString *CellIdentifier = @"myCellID"; myCell * cell = [tableVi

所以我有个问题……对我来说,在CellForRowatineXpath方法中使用dispatch\u异步代码对我来说太笨重和混乱了

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {

    static NSString *CellIdentifier = @"myCellID";
    myCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // someData - an array of dictionary for the tableview datasource
    NSURL * imageURL = [NSURL URLWithString:someData[indexPath.row][@"photoURL"]];

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(queue, ^{

            NSData *data = [NSData dataWithContentsOfURL:imageURL];
            UIImage *image = [UIImage imageWithData:data];
            dispatch_async(dispatch_get_main_queue(), ^{                    

                cell.myImageView.image = image;         

            });
        });
}
因此,经过一点研究,我的解决方案是:

-(void)loadAsyncImage:(NSIndexPath *)indexPath{

     NSURL * imageURL = [NSURL URLWithString:someData[indexPath.row][@"photoURL"] ];


    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{

        NSData *data = [NSData dataWithContentsOfURL:imageURL];
        UIImage *myImage = [UIImage imageWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{

            // _myTableView a property link from the interface builder
            myCell * cell = (id)[_myTableView cellForRowAtIndexPath:indexPath];
            cell.myImageView.image = myImage;


    });
});

}
然后在

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {

    static NSString *CellIdentifier = @"myCellID";
    myCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    [self loadAsyncImage: indexPath];
}

令我惊讶的是,它能工作而且更干净…但是。。。我不知道这样做是否正确。有没有更好的办法解决这个问题?或者这样可以吗?

可以,但有两个问题:一个小问题:如果当前看不到该单元格,则无需重新加载该单元格(该单元格可能已滚动消失)。大问题:如果不缓存结果,您将在用户来回滚动时启动和重新启动相同的请求。请看我的回答:是的,我的代码中有缓存。只是没法把所有的东西都写出来。我真的很感谢你的反馈。我将研究您的第一期。另一个次要问题是NSURLConnection中的sendAsynch为您编写了所有GCD代码。是的,我刚刚看到了您的解决方案。太棒了!非常感谢。@danh如果手机从屏幕上滚下来,他就不会重新加载手机了。UITableView的
cellForRowAtIndexPath:
对于不可见的索引路径返回nil。