我正在做两个单独的请求来从外部源获取JSON,到目前为止我已经实现了从第一个请求到我的表视图的数据显示。我的问题是,我需要将两组数据合并到一个表视图中,并通过一个公共密钥对数据进行排序,在这种情况下是common_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;
});
答案 0 :(得分: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];