0

我正在发出两个单独的请求以从外部源获取 JSON,到目前为止,我已经实现了将第一个请求中的数据显示到我的表格视图中。我的问题是,我需要将两组数据组合到一个表视图中,并通过一个公共键对数据进行排序,在本例中是 created_time。我知道我可以使用某种形式的数组,但是我该怎么做呢?

首先:

NSURL *url = [NSURL URLWithString:myURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation
                                     JSONRequestOperationWithRequest:request
                                     success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) {
                                         self.results = [json valueForKeyPath:@"data"];
                                         [self.tableView reloadData];
                                     } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                                     }];

[operation start];

第二:

NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/search/tweets.json"];
             NSDictionary *parameters = @{@"count" : RESULTS_PERPAGE,
                                          @"q" : encodedQuery};

             SLRequest *slRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter
                                                     requestMethod:SLRequestMethodGET
                                                               URL:url
                                                        parameters:parameters];

             NSArray *accounts = [self.accountStore accountsWithAccountType:accountType];
             slRequest.account = [accounts lastObject];             
             NSURLRequest *request = [slRequest preparedURLRequest];
             dispatch_async(dispatch_get_main_queue(), ^{
                 self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
                 [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
             });
4

1 回答 1

0

要合并来自外部来源的数据,您需要对收到的每个响应执行以下操作。

另外,为了这个例子,我假设你要处理的对象都是字典。如果不是,您将需要在比较块中添加一些逻辑,以created_time根据每个对象的类型获取值。

NSArray *data = [json valueForKeyPath: @"data"];        // This is the data from your first example. You'll have to do the same for your second example.

NSMutableArray *allResults = [NSMutableArray arrayWithArray: self.results];
[allResults addObjectsFromArray: data];
[allResults sortUsingComparator: ^NSComparisonResult(id obj1, id obj2) {

    NSDictionary *dict1 = obj1;
    NSDictionary *dict2 = obj2;

    return [[dict1 objectForKey: @"created_time"] compare: [dict2 objectForKey: @"created_time"]];
}];

[self setResults: allResults];
[self.tableView reloadData];
于 2013-07-29T19:44:44.470 回答