您的位置:首页 > Web前端 > JavaScript

从json传递数据显示表格实例

2015-12-15 13:01 531 查看
@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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: