首页 > Web开发 > 详细

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

时间:2015-12-15 14:27:21      阅读:153      评论:0      收藏:0      [点我收藏+]
@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;
}

 

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

原文:http://www.cnblogs.com/death3721/p/5047902.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!