TableView跳过几个单元格以显示来自JSON的数据

时间:2017-10-13 16:05:27

标签: ios objective-c json uitableview

所以我能够解析JSON数据但是当我尝试在TableView中显示它时,我显示第一行,然后可能是第六行,依此类推:

enter image description here

这是我检索数据的方式:

- (void)getData{

    NSURL *url = [NSURL URLWithString:@"https://gist.githubusercontent.com/hart88/198f29ec5114a3ec3460/raw/8dd19a88f9b8d24c23d9960f3300d0c917a4f07c/cake.json"];

    NSData *data = [NSData dataWithContentsOfURL:url];

    NSError *jsonError;
    id responseData = [NSJSONSerialization
                       JSONObjectWithData:data
                       options:kNilOptions
                       error:&jsonError];
    if (!jsonError){
        self.objects = responseData;
        NSLog(@"%@", self.objects);
        [self.tableView reloadData];
    } else {
    }

}

这就是我在cellforRowAt中显示它们的方式:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CakeCell *cell = (CakeCell*)[tableView dequeueReusableCellWithIdentifier:@"CakeCell"];
[self.tableView registerClass:[CakeCell self] forCellReuseIdentifier:@"CakeCell"];

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

    NSDictionary *object = self.objects[indexPath.row];
    cell.titleLabel.text = object[@"title"];
    cell.descriptionLabel.text = object[@"desc"];


    NSURL *aURL = [NSURL URLWithString:object[@"image"]];
    NSData *data = [NSData dataWithContentsOfURL:aURL];
    UIImage *image = [UIImage imageWithData:data];
    [cell.cakeImageView setImage:image];

});

return cell;
}

1 个答案:

答案 0 :(得分:2)

问题是您从后台线程访问UIKit元素。您可以通过以下方式重构它。

nil


如果您需要通过后台操作来进行某些UI更新,请始终将此代码包装在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CakeCell *cell = (CakeCell*)[tableView dequeueReusableCellWithIdentifier:@"CakeCell"]; [self.tableView registerClass:[CakeCell self] forCellReuseIdentifier:@"CakeCell"]; NSDictionary *object = self.objects[indexPath.row]; cell.titleLabel.text = object[@"title"]; cell.descriptionLabel.text = object[@"desc"]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); dispatch_async(queue, ^(void) { NSURL *aURL = [NSURL URLWithString:object[@"image"]]; NSData *data = [NSData dataWithContentsOfURL:aURL]; UIImage *image = [UIImage imageWithData:data]; dispatch_async(dispatch_get_main_queue(), ^{ [cell.cakeImageView setImage:image]; }); }); return cell; } 调用