【问题标题】:I want to populate my tableview from my NSDictionary我想从我的 NSDictionary 填充我的 tableview
【发布时间】:2012-09-17 02:53:17
【问题描述】:
- (void)receiveData:(NSData *)data {
    self.office = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    self.files = [office objectForKey:@"files"];
    [self.myTableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.files.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] init];

    NSDictionary *file = [self.files objectAtIndex:indexPath.row];
    cell.textLabel.text = [file objectAtIndex:1];  //here i want to get data from the array
    cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
    cell.textLabel.numberOfLines = 1;
    return cell;
    NSLog(@"files:\n%@", file);
}

我有一个 json 响应,我存储在 NSDictionary 办公室中,并且该 json 中的数组存储在 NSArray 文件中,现在我已将文件数组提供给另一个 NSDictionary 文件,并根据存储在该文件中的数据我想要该数据在我的表格行中,但我的文件数组中没有任何“键”,只有该数组中的值,

所以我的问题是,我如何在我的文件字典中指出该值,我已在我想要的地方发表评论,请查看该评论....

【问题讨论】:

  • 你为什么不用[file objectAtIndex:indexPath.row];
  • [文件 objectAtIndex:indexPath.row]; //不起作用
  • [文件 objectAtIndex:indexPath.row]; //有效
  • 没有键的字典怎么办?
  • 记录文件并检查您想要显示和使用的内容..

标签: iphone ios json uitableview


【解决方案1】:

JSON 解析器 NSJSONSerialization 可能没有创建您认为拥有的 NSDictionary/NSArray 结构。您必须检查您的 JSON,例如使用jsonlint.com,然后使用 NSLog 查看您的字典/数组中放置的内容。还可以尝试一些 NSJSONReadingOptions 选项。

【讨论】:

    【解决方案2】:

    我认为你要么误解了 NSDictionary 的工作原理,要么你在 self.files 中访问的对象实际上并不是 NSDictionaries。如果它们实际上是 NSDictionary 对象,则需要像 runmad 所说的那样访问它们

    [file objectForKey:@"keyName"]
    

    如果没有键,那么您正在处理不同类型的对象,我们需要了解更多细节才能为您提供帮助。当您发布问题时,runmad 给了您正确的答案。

    【讨论】:

    • self.files 不是 NSDictionary 它是一个数组,我已经将该数组放入 NSDictionary 文件中,但现在我已经放弃了这个想法并像这样将数组提供给单元格
    • cell.textLabel.text = [self.files objectAtIndex:indexPath.row];
    【解决方案3】:

    您正在创建字典:

    NSDictionary *file = [self.files objectAtIndex:indexPath.row];
    

    NSDictionary 使用键进行索引,因此您必须使用 objectForKey: 获取字符串

    cell.textLabel.text = [file objectForKey:@"fileName"];
    

    【讨论】:

    • 这对我不起作用,我说我的数组只包含值不包含任何键,所以 [file objectForKey:@"fileName"] 不起作用。
    • 您可能想发布file 的输出,当我们不知道您的数据结构时,任何人都很难提供帮助
    • cell.textLabel.text = [self.files objectAtIndex:indexPath.row];
    • 我给那个单元格的东西有什么不同,因为它解决了我的问题
    • 嗯,如果它解决了你的问题,它显然会有所作为。您可能想了解 NSArray 和 NSDictionary 之间的区别:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多