将NSMutableArray转换为NSDictionary以使用objectForKey?

时间:2012-01-06 02:31:18

标签: iphone objective-c cocoa-touch nsarray nsdictionary

我有一个看起来像这样的NSMutableArray

 {
    "@active" = false;
    "@name" = NAME1;
 },
 {
    "@active" = false;
    "@name" = NAME2;
 }

有没有办法将其转换为NSDictionary,然后使用objectForKey来获取名称对象的数组?我怎么能得到这些物品?

6 个答案:

答案 0 :(得分:7)

这是休伯特提出的更短的形式

NSArray *allNames = [array valueForKey:@"name"];
NSArray上的

valueForKey:通过向所有元素发送valueForKey:givenKey来返回一个新数组。

来自docs

  

valueForKey:
  返回包含调用结果的数组   valueForKey:在每个数组的对象上使用key

     

- (id)valueForKey:(NSString *)key

     

<强>参数
  key要检索的密钥。

     

返回值
  检索到的密钥的值。

     

<强>讨论
  返回的数组包含返回NSNull的每个对象的nil个元素。

示例:

NSArray *array = @[@{ @"active": @NO,@"name": @"Alice"},
                   @{ @"active": @NO,@"name": @"Bob"}];

NSLog(@"%@\n%@", array, [array valueForKey:@"name"]);

结果:

(
        {
        active = 0;
        name = Alice;
    },
        {
        active = 0;
        name = Bob;
    }
)
(
    Alice,
    Bob
)

答案 1 :(得分:3)

这是一个Dictionary对象数组,所以要得到你想要的值:

[[myArray objectAtIndex:0]valueForKey:@"name"]; //Replace index with the index you want and/or the key.

答案 2 :(得分:3)

如果您想将NSMutableArray转换为相应的NSDictionary,只需使用mutableCopy

NSMutableArray *phone_list; //your Array
NSDictionary *dictionary = [[NSDictionary alloc] init];
dictionary = [phone_list mutableCopy];

答案 3 :(得分:1)

是的,你可以

见这个例子:

NSDictionary *responseDictionary = [[request responseString] JSONValue];
NSMutableArray *dict = [responseDictionary objectForKey:@"data"];
NSDictionary *entry = [dict objectAtIndex:0];
NSString *num = [entry objectForKey:@"num"]; 
NSString *name = [entry objectForKey:@"name"];
NSString *score = [entry objectForKey:@"score"];

对不起,如果我不能详细说明,因为我也在做一些事情

但我希望能帮到你。 :)

答案 4 :(得分:1)

这是示例之一,获取emplyee列表NSMutableArray并创建NSMutableDictionary .......

NSMutableArray *emloyees = [[NSMutableArray alloc]initWithObjects:@"saman",@"Ruchira",@"Rukshan",@"ishan",@"Harsha",@"Ghihan",@"Lakmali",@"Dasuni", nil];

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in emloyees) {
    NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
    letterList  = [dict objectForKey:firstLetter];

    if (!letterList) {
        letterList = [NSMutableArray array];
        [dict setObject:letterList forKey:firstLetter];
    }
    [letterList addObject:word];
}   NSLog(@"dic %@",dict);

答案 5 :(得分:0)

不,伙计......问题是你正在踩着可可的KeyValue机制。

KeyValueCoding指定@count符号可用于keyPath ....

myArray的。@计数

SOOOOOO ....只需切换到ObjectForKey即可!

NSMutableDictionary *myDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"theValue", @"@name", nil];

id kvoReturnedObject = [myDictionary valueForKey:@"@name"]; //WON'T WORK, the @ symbol is special in the valueForKey
id dictionaryReturnedObject = [myDictionary objectForKey:@"@name"];

NSLog(@"object = %@", dictionaryReturnedObject);