无法从词典

时间:2016-04-23 07:10:36

标签: ios objective-c nsmutablearray nsmutabledictionary

在我的项目中,我以

的形式从服务器获得响应
response:  

     <JKArray 0x7fa2e09036b0>(
        {
            id = 23;
            name = "Name1";    
        },
        {
            id = 24;
            name = "Name2";   
        }

    )

从这个响应数组中,我检索不同索引的对象,然后将它们添加到mutableArray中,然后添加到contactsDictionary中。

  self.contactsDictionary = [[NSMutableDictionary alloc] init];    

            for(int i=0 ; i < [response count] ; i++)
            {
                NSMutableArray *mutableArray=[[NSMutableArray alloc] init];
                [mutableArray addObject:[response objectAtIndex:i]];

                [self.contactsDictionary setObject:mutableArray forKey:[NSString stringWithFormat:@"%i",i]];

            }

我想从项目中某个其他位置的contactsDictionary检索Key @“name”的数据。那怎么做呢。 提前谢谢....

2 个答案:

答案 0 :(得分:0)

这是你设置contactsDictionary的错误方法。

替换下面的行

[self.contactsDictionary setObject:mutableArray forKey:[NSString stringWithFormat:@"%i",i]];

[self.contactsDictionary setObject:[mutableArray objectAtIndex :i] forKey:[NSString stringWithFormat:@"%i",i]];

因为每次你的数组都有新对象,所以你的联系人字典的第一个值有一个对象,然后第二个值有两个对象。所以你不应该这样做。

现在,如果您想要检索name,请调用

 NSString *name = [[self.contactsDictionary objectForKey : @"1"]valueForKey : @"name"];

如果有的话,请避免语法错误,因为这里输入了ans。

根据评论更新:

为exa选择一个mutablearray,

 NSMutableArray *arr = [[NSMutableArray alloc]init];
 [arr addObject : name];  //add name string like this

希望这会有所帮助:)

答案 1 :(得分:0)

Aloha从你的回复中我可以根据你的回应给你这样的回答。

for(int i=0;i<[arrRes count];i++);
{
   NSString *strId = [NSString stringWithFormat:@"%@",[[arrRes obectAtIndex:i]objectForKey:@"id"]];
   NSString *StrName = [NSString stringWithFormat:@"%@",[[arrRes objectAtIndex:i]objectForKey:@"name"]];

   NSLog(@"The ID is -%@",strId);
   NSLog(@"The NAME is - %@",strName);

  }