0

我有 json 数据,现在我想推入表格视图?但最初,我必须获取 json 数据,以便推荐使用哪个调度方法或子线程,以便我可以在后台加载数据然后推送它。

4

1 回答 1

0

最佳实践是使用 dispatch_async 方法在后台线程中加载数据并传递除 main 之外的队列,这样它就不会阻塞 UI,当你准备好数据时,只需在主线程上调用 reload table view ... 下面是一个示例真正的项目......类级方法加载事务

+ (void)getAllTransactionsWithHandler:(void(^)(NSArray *transactions, NSError *error))handler{
    dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(q, ^{
        NSURL *url = [[NSBundle mainBundle] URLForResource:trnasactionFileName withExtension:@"json"];//[NSData dataWithContentsOfFile:trnasactionFileName];
        NSData *data = [NSData dataWithContentsOfURL:url];
        if (!data) {
            if (handler) {
                handler(nil, [NSError errorWithDomain:@"bank" code:900 userInfo:nil]);
            }
            return ;
        }
        NSError *error = nil;
        NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        if (error) {
            if (handler) {
                handler(nil, error);
            }
        }
        else{
            Transaction *transaction;
            NSString *dateString;
            NSMutableArray *objects = [NSMutableArray new];
            for (NSDictionary *dic in jsonArray) {
                transaction = [Transaction new];
                 dateString = dic[kOccured];
                NSDateFormatter *dateFormater = [NSDateFormatter new];
                [dateFormater setDateFormat:@"yyyy-MM-dd"];
                transaction.occured = [dateFormater dateFromString:dateString];
                transaction.proecessed = [dateFormater dateFromString:dic[kProcessed]];
                transaction.desc = dic[kDescription];
                transaction.amount = dic[kAmount];
                [objects addObject:transaction];
            }
            if (handler) {
                handler([NSArray arrayWithArray:objects], nil);
            }
        }

    });
}

您可以将其用作

 [Transaction getAllTransactionsWithHandler:^(NSArray *transactions, NSError *error) {
        if (error) {

        }else{
            if ([transactions count] > 0) {
                weakSelf.objects = transactions;
                runOnMainThread(^{
                    [weakSelf.tableView reloadData];
                });


            }
        }
    }];

runOnMainthread 是一种实用方法,它将在主线程上运行提供的代码块

void runOnMainThread(void(^block)(void)){
    if ([[NSThread currentThread] isMainThread])
        block();
    else{
        dispatch_sync(dispatch_get_main_queue(), ^{
            block();
        });
    }
}
于 2014-10-03T18:34:58.517 回答