@interface ViewController (){
NSMutableArray *_arr;
NSString *_newElementName;
hero *_hero;
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:UITableViewStylePlain];
_tbv.delegate = self;
_tbv.dataSource = self;
[self.view addSubview:_tbv];
AFURLSessionManager *manager = [[AFURLSessionManager alloc]init];
manager.responseSerializer = [[AFJSONResponseSerializer alloc]init];
NSURL *url = [NSURL URLWithString:TEST_URL];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSURLSessionTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
#if 0
//二进制解析器
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:responseObject];
parser.delegate = self;
[parser parse];
#elif 0
//SAX 解析器
NSXMLParser *parser = (NSXMLParser *)responseObject;
parser.delegate = self;
[parser parse];
#elif 0
//如果是http二进制解析器
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
#elif 1
//使用json解析器
NSDictionary *dic = (NSDictionary *)responseObject;
NSLog(@"===%@",dic);
#endif
}];
[task resume];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return _arr.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];
}
cell.textLabel.text = [[_arr objectAtIndex:indexPath.row]name];
cell.detailTextLabel.text = [[_arr objectAtIndex:indexPath.row]kind];
return cell;
}
- (void)parserDidStartDocument:(NSXMLParser *)parser{
_arr = [[NSMutableArray alloc]init];
}
- (void)parserDidEndDocument:(NSXMLParser *)parser{
dispatch_barrier_async(dispatch_get_main_queue(), ^{
[self->_tbv reloadData];
});
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary *)attributeDict{
if ([_newElementName isEqualToString:@"hero"]) {
_hero = [[hero alloc]init];
[_arr addObject:_hero];
}
_newElementName = elementName;
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName{
_newElementName = nil;
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([_newElementName isEqualToString:@"name"]) {
_hero.name = string;
}else if ([_newElementName isEqualToString:@"kind"]){
_hero.kind = string;
}
需要创建一个类 定义一个属性名字!!