2013-07-29 22 views
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; 
      }); 

回答

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]; 
+0

請注意,您可以執行'[allResults sortUsingComparator:^ NSComparisonResult(NSDictionary * dict1,NSDictionary * dict2){'。另外,你應該明確實施Jason建議的檢查(事實上,它是一個NSDictionary)。否則,如果您的API發送錯誤的響應,則可能會導致應用程序崩潰。 –

相關問題