计算字典对象中的值的数量

时间:2012-12-13 09:14:32

标签: ios uitableview

<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(@"Number of rows: %d",[[products objectForKey:@"products"] count]);
        return [[products objectForKey:@"products"] count];
    }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:@"cell"];
        }
        NSString *currentProductName;
        currentProductName = [productKeys objectAtIndex:indexPath.row];
        NSLog(@"product name : %@", currentProductName);
        [[cell textLabel] setText:currentProductName];

        return cell;
    }

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

此致

1 个答案:

答案 0 :(得分:3)

问题是你发布的不是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。

你应该能够重现这一点。

相关问题