【发布时间】:2011-03-14 22:54:34
【问题描述】:
我有一个关于将 JSON 数据放入表格视图的问题。我已经成功解析了数据,因为它出现在我的控制台中 - 但我一生都无法弄清楚如何将这些数据放入我的表格视图中。我花了整整一周的时间试图让它发挥作用,尝试在阳光下尝试各种组合。
大多数时候它只是崩溃,有时它告诉我“[NSCFString count]:无法识别的选择器”,我相信这是因为我试图计算一个引发异常的字符串? - 无论如何,使用下面的代码,它只是在控制台中打印我想要的数据,并在表格视图中向我显示一堆灰线,所以它不会崩溃(这是我目前能做的最好的事情)。
任何有关如何使用所有 eventNames 填充表格的帮助/建议将不胜感激。我对这个视图的最终计划是让列表中的 eventNames 在选择时推送一个新的视图控制器,显示该特定事件的数据。
这里是视图做的加载方法:
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://myurl........."];
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
NSLog(jsonreturn); //successfully returns the result of the page
//to parse it i have made a sbjsonparser object
SBJsonParser *json = [[SBJsonParser new] autorelease];
NSError *jsonError;
NSDictionary *parsedJSON = [json objectWithString:jsonreturn error:&jsonError];
//if successful, i can have a look inside parsedJSON - its worked as an NSdictionary and NSArray
NSArray* events = [parsedJSON objectForKey:@"Events"];
//eventNameList = [parsedJSON objectForKey:@"Events"];
NSLog(@"show me events: %@", events);
//NSLog(@"show me events: %@", eventNameList);
//lets try and get to rows
//NSEnumerator *enumerator = [events objectEnumerator];
NSEnumerator *enumerator = [events objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
NSLog(@"event item:eventName = %@", [item objectForKey:@"EventName"]); //everything to this point works and shows in the console
}
}
这是表格视图代码:
//customise the number of sections in the table view
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
//customise number of rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [eventNameList count];
NSLog(@"here");
}
//customise the appearance of table view cells
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
//try to get a reusable cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//create a new cell if there is not reusable cell available
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
//set the text display for the cell
NSString *cellValue = [eventNameList objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
//NSLog(@"event item from table view:eventName = %@", eventNameList);
return cell;
}
在此先感谢,任何帮助或指点都非常欢迎和赞赏:)
【问题讨论】:
-
什么失败了?您是否尝试过记录 cellValue 字符串?并确保它已设置好?
标签: iphone json parsing uitableview