因为我是 Stackoverflow 的新手,所以我还不能评论某人的答案。 (我的声誉是 16..)。我有一个关于这个答案的问题:How do I put this JSON data into my table view? Please help me, I'm living in a nightmare :)
Fulvio说你必须使用 [eventNameList addObject:event];
和 [eventNameList objectAtIndex:indexPath.row];
来存储和获取事件数据但是。 addObject 是一个 NSMutableSet 方法,而 objectAtIndex:indexPath.row 不是。所以我不能使用这种方法从 NSMutableSet 中获取数据。
除此之外,我也不能使用计数方法。
有什么想法吗?
最佳答案
假设你有一个 NSDictionary,你可以使用 [dictionary allKeys] 方法来检索一个包含所有键的数组(我们暂时称它为 keyArray)。对于 rowCount,您可以返回此 keyArray 中的对象数。要获取需要在单元格中显示的项目,您可以使用 [dictionary objectForKey:[keyArray objectAtIndex:indexPath.row]]] 为显示的单元格获取适当的字典。
在代码中:
// use the keyArray as a datasource ...
NSArray *keyArray = [jsonDictionary allKeys];
// ------------------------- //
// somewhere else in your code ...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [keyArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// set some cell defaults here (mainly design) ...
}
NSString *key = [keyArray objectAtIndex:indexPath.row];
NSDictionary *dictionary = [jsonDictionary objectForKey:key];
// get values from the dictionary and set the values for the displayed cell ...
return cell;
}
@Tieme:显然您使用的 URL 已经返回一个数组,您实际上不需要处理字典(您可以只使用数组作为数据源),请查看以下内容:
SBJSON *json = [[[SBJSON alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:@"http://www.my-bjoeks.nl/competitions/fetchRoutes/25.json"];
NSString *string = [[[NSString alloc] initWithContentsOfURL:url] autorelease];
NSError *jsonError = nil;
id object = [json objectWithString:string error:&jsonError];
if (!jsonError) {
NSLog(@"%@", object);
NSLog(@"%@", [object class]); // seems an array is returned, NOT a dictionary ...
}
// if you need a mutableArray for the tableView, you can convert it.
NSMutableArray *dataArray = [NSMutableArray arrayWithArray:object]
关于objective-c - NSDictionary 到 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5701314/