【问题标题】:Count number of values in dictionary object计算字典对象中的值数
【发布时间】:2012-12-01 03:29:59
【问题描述】:
<pre>
    products =     (
                {
            id = 19;
            "image_url" = "http://localhost:8888/straightoffer/image/data/1330374078photography.jpg";
            name = "Save $240 on your next photo session";
        },
                {
            id = 21;
            "image_url" = "http://localhost:8888/straightoffer/image/data/1330373696massage.jpg";
            name = "One Hour  Massage";
        }
    );
}
</pre>

以上是我通过json得到的,需要给uitableviews赋值:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ NSLog(@"行数:%d",[[products objectForKey:@"products"] count]); 返回 [[products objectForKey:@"products"] count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; 如果(细胞 == 零){ 单元格 = [[UITableViewCell 分配] initWithStyle:UITableViewCellStyleDefault 重用标识符:@“细胞”]; } NSString *currentProductName; currentProductName = [productKeys objectAtIndex:indexPath.row]; NSLog(@"产品名称:%@", currentProductName); [[单元格文本标签] setText:currentProductName]; 返回单元格; }

它返回 0 行数,我是 ios 的新手,请帮助我如何将这些值分配给 uitableview。

问候

【问题讨论】:

  • 我需要更多信息。这段代码看起来不错。这个故事的数据检索部分出了问题。你能添加你如何填写products字典的代码吗?
  • 你能登录products 并告诉我们..?如果products 本身就是数组,你可以算对吗?
  • products = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];这就是产品的填充方式,并且当我使用第一个有问题的 pre 标签记录内容时
  • 检查numberOfRowsInSectionproducts 是否有值或无
  • numberOfRowsInSection 返回 nil

标签: ios uitableview


【解决方案1】:

问题是你发布的不是json。应该是

{
    "products":[
        {
            "id":19,
            "image_url":"http://localhost:8888/straightoffer/image/data/1330374078photography.jpg",
            "name":"Save $240 on your next photo session"
        },
        {
            "id":21,
            "image_url":"http://localhost:8888/straightoffer/image/data/1330373696massage.jpg",
            "name":"One Hour  Massage"
        }
    ]
}

您可以使用http://jsonlint.com/ 来验证您的 json 文件。



我已经使用了上面的 json 文件并做了以下操作:

NSBundle* bundle = [NSBundle mainBundle];
NSString *jsonPath = [bundle pathForResource:@"data" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:jsonPath];

NSError *error;
NSDictionary *products = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

DLog(@"products: %i", [[products objectForKey:@"products"] count] );

[self.tableView reloadData];

结果是:产品:2。

你应该能够重现这个。

【讨论】:

  • 我生成的实际json和你提到的一样,我在这里打印ios记录的内容。 json 是有效的,我已经检查了你提供的 url。
  • 是的,我需要更多帮助,因为我的 json 格式是正确的。
  • 我已经指出,带有我原始代码的产品在 viewDidLoad 方法中填充得很好,但是当我调用 numberOfRowsInSection 时它返回 0,为什么会这样。
  • 你添加了[self.tableView reloadData];数据加载后?
  • 我应该在哪个方法上添加这个?
猜你喜欢
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多