@interface ViewController (){
NSDictionary *_dic;
UITableView *_tbv;
}
@end
#define TEST_URL @"HTTP://127.0.0.1/1604C.json"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_tbv = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
_tbv.delegate = self;
_tbv.dataSource = self;
[self.view addSubview:_tbv];
// Do any additional setup after loading the view, typically from a nib.
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task = [session dataTaskWithURL:[NSURL URLWithString:TEST_URL] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
#if 0
//系统自带的方式解析
self->_dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
#elif 1
//SBJson
SBJsonParser *js = [[SBJsonParser alloc]init];
self->_dic = [js objectWithData:data];
#elif 0
//json kit
self->_dic = [data objectFromJSONData];
#endif
//回到主线程
dispatch_async(dispatch_get_main_queue(), ^{
[self->_tbv reloadData];
});
}];
[task resume];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return _dic.allKeys.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSString *key = [_dic.allKeys objectAtIndex:section];
return [[_dic objectForKey:key]count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
}
NSString *key = [_dic.allKeys objectAtIndex:indexPath.section];
cell.textLabel.text = [[[_dic objectForKey:key]objectAtIndex:indexPath.row]objectForKey:@"name"];
cell.detailTextLabel.text = [[[_dic objectForKey:key]objectAtIndex:indexPath.row]objectForKey:@"like"];
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [_dic.allKeys objectAtIndex:section];
}
网友评论