既然JSON这么好,它怎么和UITableView结合使用呢?
首先看看我们的JSON文件吧:
{ "老张家":["大张","二张","三张"], "老李家":["大李","二李"] }
完成的作品是这样样子的~~(点击放大阿~~)
好,开始打代码吧。
1,首先copy JSON库到当前的Project里面。
2,建立一个数据源类。我给它起名叫MyDataSource, 看看里面都有什么吧:
dataSource; @end #import "JSON.h" @implementation MyDataSource dataSource JSONString stringWithContentsOfFilemainBundleofTypeencoding; return [JSONString JSONValue]; } @end
里面非常简单,只有一个类方法dataSource。在其中我们读取json文件的内容到一个NSString中,并用JSON框架来解读成一个NSDictionary,返回值为id。因为虽然大多的时候最外的对象都为NSDictionary,但是出于严谨,万一是NSArray不就崩溃了。所以使用id,这样其实就有再次可以用的特性了。
3,建立一个UITableViewController, 然后作适当的设置:
#import "MyTableViewController.h" #import "MyDataSource.h" @implementation MyTableViewController initWithStyle:(UITableViewStyle)style self myData MyDataSource dataSource] retain]; self; } #pragma mark Table view methods UITableView myData count]; //有多少个section,也就是“几家” } UITableView NSIntegermyData valueForKeymyData allKeys] objectAtIndex:section]] count]; //这里我们需要告诉UITableViewController每个section里面有几个,也就是“一家里面有几口人” } tableViewtableView cellForRowAtIndexPathindexPath { CellIdentifier ; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; cell UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } //上面的东西都是重复白给的,平时没事不用想为什么,照抄就可以了 cell.textLabel.text myData valueForKeymyData allKeys] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]; cell; } tableViewtableView titleForHeaderInSection:(NSInteger)section myData allKeys] objectAtIndex:section]; dealloc super dealloc]; } @end
4,在主程序代理 xxxAppDelegate 里面初始化这个UITableViewController然后添加它的view到window的subview中就OK拉!
5,编译运行,没有错误就万事大吉!大吉!
阿弥陀佛,祝各位愉快~
第一期请参看iPhone上的JSON第二期请参看iPhone上的JSON(二)