重构uitableviewcell异步图像加载

时间:2014-04-11 15:27:48

标签: ios uitableview grand-central-dispatch

所以我有问题...对我来说,在cellForRowAtIndexPath方法中使用dispatch_async代码对我来说太笨重和混乱。

- (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];
}

令我惊讶的是它有效并且更清洁......但......我不知道这是否是正确的方法。有没有更好的方法来解决这个问题?或者这样可以吗?

0 个答案:

没有答案