iPhone:如何使用键从NSMutableArray获取值

时间:2012-01-03 10:34:21

标签: iphone objective-c nsdictionary

我想知道如何使用键从NSMutableArray中获取值。该数组的构建如下:

    qtype = [[NSMutableArray alloc] init];
    while (dicjson = (NSDictionary*)[enumerator nextObject]) {
     question_id = [dicjson objectForKey:@"question_id"];        
     question_text = [dicjson objectForKey:@"question_text"];
     question_type = [dicjson objectForKey:@"question_type"];

     [qtype addObject:[NSDictionary dictionaryWithObject:question_type forKey:question_id]];

} 

我在表格单元格中填充数组:

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *type = [qtype objectAtIndex:[indexPath row]];

}

然而输出就像“65 = YN”,这不是我想要的。我想只提取“65”。 如果你能给我一些想法,我将非常感激。

4 个答案:

答案 0 :(得分:1)

似乎问题类型的字典只包含一个键,因此您可以实现您想要的效果,但请记住:字典是使用键的无序集合,而数组是 ordered < / strong>使用索引的集合。

无论如何,在tableView:cellForRowAtIndexPath:中,修改代码以获取字典中唯一的键(这是问题ID):

-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *dictKeys = [[qtype objectAtIndex:[indexPath row]] allKeys];
    NSString *type = [dictKeys objectAtIndex:0];
}

答案 1 :(得分:1)

事实上,我真的不明白你为什么要使用一系列词典 您可以简单地构建问题文本数组:

qtype = [[NSMutableArray alloc] init];
while (dicjson = (NSDictionary*)[enumerator nextObject]) {
 question_id = [dicjson objectForKey:@"question_id"];        
 question_text = [dicjson objectForKey:@"question_text"];
 question_type = [dicjson objectForKey:@"question_type"];

 [qtype addObject:question_id];

 } 

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *type = [qtype objectAtIndex:[indexPath row]];

}

但如果你需要qtype用于其他目的,你可以得到

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = [qtype objectAtIndex:[indexPath row]];
    NSString *type = [[dict allKeys] objectAtIndex:0]; 

}

答案 2 :(得分:0)

这是因为您将NSDictionary存储在“qtype”中。尝试:

NSDictionary *dict = [qtype objectAtIndex:[indexPath row]];
NSString *type = [[dict allValues] lastObject];//since you have only one object stored.

答案 3 :(得分:0)

您可以访问NSDictionary类型的数组的每个对象。以下是该代码

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = [qtype objectAtIndex:[indexPath row]];
    NSString *question_id = [dict objectForKey:@"question_id"];     
    NSString *question_text = [dict objectForKey:@"question_text"];
    NSString *question_type = [dict objectForKey:@"question_type"];
}