@interface ViewController ()<UITableViewDataSource,UITableViewDelegate> { UITableView* table; NSMutableArray* parseResult; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //获取本地json文件 NSString* jsonPath=[[NSBundle mainBundle]pathForResource:@"books" ofType:@"json"]; //把json文件转成NSData类型 NSData* data=[NSData dataWithContentsOfFile:jsonPath]; //解析json数据 返回OC对象 数据转对象用JSONObjectWithData方法 parseResult=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; table=[[UITableView alloc]initWithFrame:CGRectMake(0, 20, 320, 568-20) style:UITableViewStylePlain]; table.dataSource=self; table.delegate=self; [self.view addSubview:table]; //把NSData文件解析json成数据 NSData* data1=[NSJSONSerialization dataWithJSONObject:parseResult options:0 error:nil]; //把NSData文件转成NSString格式 用于直接输出 NSString* json=[[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding]; NSLog(@"%@",json); } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; { return parseResult.count; } #pragma mark 表示每一行显示什么数据 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; { //内存优化 static NSString * identity=@"cell"; //tableview 根据标识复制出一个cell UITableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:identity]; if (cell==nil) { cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identity]; } NSDictionary* dic=parseResult[indexPath.row]; cell.textLabel.text=[dic valueForKey:@"title"]; cell.detailTextLabel.text=[dic valueForKey:@"author"]; cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator; return cell; }
原文:http://www.cnblogs.com/death3721/p/5047902.html