本文摘自:http://c.gzl.name/archives/tag/uitableviewcontroller
既然JSON這麼好,它怎麼和UITableView結合使用呢?
首先看看我們的JSON檔案吧:
{"老張家":["大張","二張","三張"],"老李家":["大李","二李"]}
完成的作品是這樣樣子的~~(點擊放大阿~~)
好,開始打代碼吧。
1,首先copy JSON庫到當前的Project裡面。
2,建立一個資料來源類。我給它起名叫MyDataSource, 看看裡面都有什麼吧:
@interface MyDataSource : NSObject {}+ (id)dataSource;@end #import "JSON.h" @implementation MyDataSource+ (id)dataSource{NSString* JSONString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"] encoding:NSUTF8StringEncoding error:nil];return [JSONString JSONValue];}@end
裡面非常簡單,只有一個類方法dataSource。在其中我們讀取json檔案的內容到一個NSString中,並用JSON架構來解讀成一個NSDictionary,傳回值為id。因為雖然大多的時候最外的對象都為NSDictionary,但是出於嚴謹,萬一是NSArray不就崩潰了。所以使用id,這樣其實就有再次可以用的特性了。
3,建立一個UITableViewController, 然後作適當的設定:
#import "MyTableViewController.h"#import "MyDataSource.h" @implementation MyTableViewController - (id)initWithStyle:(UITableViewStyle)style{if (self = [super initWithStyle:style]) {myData = [[MyDataSource dataSource] retain];//在這裡我們初始化myData,其實就是一個id對象//傳入由MyDataSource解析出的NSDictionary}return self;} #pragma mark Table view methods - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [myData count]; //有多少個section,也就是“幾家”} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [[myData valueForKey:[[myData allKeys] objectAtIndex:section]] count];//這裡我們需要告訴UITableViewController每個section裡面有幾個,也就是“一家裡面有幾口人”} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } //上面的東西都是重複白給的,平時沒事不用想為什麼,照抄就可以了cell.textLabel.text = [[myData valueForKey:[[myData allKeys] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];//這句看上去複雜,但是其實不過是在特定section裡面找到對應的array,//然後在array中找到indexPath.row所在的內容 return cell;} - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{return [[myData allKeys] objectAtIndex:section];//這裡設定對應section的名字,很簡單allKey返回所有的索引值為一個array,也就是“張家”,“李家”//然後用objectAtIndex: 來找出究竟是哪一個就可以了!} - (void)dealloc { [myData release]; //“我們是runtime的好市民”...release就好Alan...... [super dealloc];}@end
4,在主程式代理 xxxAppDelegate 裡面初始化這個UITableViewController然後添加它的view到window的subview中就OK拉!
5,編譯運行,沒有錯誤就萬事大吉!大吉!