数据从JSON直接解析到UITableView [英] Data from JSON Parsing straight to UITableView
问题描述
我正在使用带有此代码的json来获取数据,我需要在带有两个部分代码的表视图中显示数据,并命名问题是将其全部写到一个数组上需要花费很多时间,而该数组又返回null.如何获得每个返回的元素作为自己的tableview单元格?返回了数百个机场.
I am getting data using json with this code and I need to display it in a tableview with two part code and name the problem is writing it all to an array is taking forever and the array comes back null. How can I get each returned element as its own tableview cell? Hundreds of airports are returned.
NSString* path = @"https://api.flightstats.com/flex/airports/rest/v1/json/active?appId=id&appKey=appkey";
NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
[_request setHTTPMethod:@"GET"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
if(nil != error)
{
NSLog(@"Error: %@", error);
}
else
{
NSMutableDictionary* json = nil;
if(nil != _connectionData)
{
json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
}
if (error || !json)
{
NSLog(@"Could not parse loaded json with error:%@", error);
}
else
{
NSMutableDictionary *routeRes;
routeRes = [json objectForKey:@"airports"];
for(NSMutableDictionary *flight in routeRes)
{
NSLog(@"ident is %@", [flight objectForKey:@"name"]);
NSString *code=[json objectForKey:@"fs"];
NSString *name=[flight objectForKey:@"name"];
NSLog(@"code %@, name %@", code, name);
[candyArray addObject:[Candy code:code name:name]];
}
}
_connectionData = nil;
NSLog(@"connection done");
以下是cellForRowatIndex,但未显示任何内容
The following is the cellForRowatIndex were nothing is shown
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if ( cell == nil ) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Create a new Candy Object
Candy *candy = nil;
// Check to see whether the normal table or search results table is being displayed and set the Candy object from the appropriate array
if (tableView == self.searchDisplayController.searchResultsTableView)
{
candy = [filteredCandyArray objectAtIndex:[indexPath row]];
}
else
{
candy = [candyArray objectAtIndex:[indexPath row]];
}
// Configure the cell
[[cell textLabel] setText:[candy name]];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
这是返回的json是一个示例
This is a sample of what the returned json is
{"airports":[{"fs":"CLO","iata":"CLO","icao":"SKCL","name":"Alfonso B. Aragon Airport","city":"Cali","cityCode":"CLO","countryCode":"CO","countryName":"Colombia","regionName":"South America","timeZoneRegionName":"America/Bogota","localTime":"2014-03-31T18:51:58.372","utcOffsetHours":-5.0,"latitude":3.543056,"longitude":-76.381389,"elevationFeet":3162,"classification":3,"active":true,"delayIndexUrl":"https://api.flightstats.com/flex/delayindex/rest/v1/json/airports/CLO?codeType=fs","weatherUrl":"https://api.flightstats.com/flex/weather/rest/v1/json/all/CLO?codeType=fs"}
这是搜索功能:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
// Update the filtered array based on the search text and scope.
// Remove all objects from the filtered search array
[self.filteredCandyArray removeAllObjects];
// Filter the array using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];
NSArray *tempArray = [airportsArray filteredArrayUsingPredicate:predicate];
NSLog(@" text %@", searchText);
filteredCandyArray = [NSMutableArray arrayWithArray:tempArray];
NSLog(@"NSLog %@", scope);
}
推荐答案
那个糖果对象怎么了?
您有一个字典数组,这是解析它的方法:
You have an array of dictionnary, here's how you parse that:
获取数组:
NSArray *airportsArray = [json objectForKey:@"airports"];
设置单元格文本:
[[cell textLabel] setText:[[airportsArray objectAtIndex:indexPath.row]objectForKey:@"name"]];
[[cell detailTextLabel] setText:[[airportsArray objectAtIndex:indexPath.row]objectForKey:@"code"]];
或为了提高可读性:
NSDictionary *airportAtIndex = [airportsArray objectAtIndex:indexPath.row];
[[cell textLabel] setText:[airportAtIndex objectForKey:@"name"]];
[[cell detailTextLabel] setText:[airportAtIndex objectForKey:@"code"]];
您能否详细说明如何使用sendAsynch来加快过程?
Can you elaborate on how I could use sendAsynch to speed up the process?
好的,首先要注意的是,您不是在这里加速任何事情,感觉UI滞后的原因是因为您在主线程上运行了网络请求.
Ok, first thing to note, you are not speeding up anything here, the reason why you feel the UI is lagging is because you run the network request on the main thread.
您可以通过异步发送请求来解决该问题,这意味着在后台线程中不会冻结您的用户界面.
You can solve that problem by sending the request asynchrously, meaning in a background thread which will not freeze your User Interface.
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//this is where you perform the network request
//You can fetch data, in your case get the JSON
dispatch_async(dispatch_get_main_queue(), ^(void){
//in this block you want to manipulate the the User Interface
//this is where you reload the tableView
//or stop an activity indicator
[self.tableView reloadData];
});
});