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

@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;
}

 

转载于:https://www.cnblogs.com/death3721/p/5047902.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值