I have an NSMutableArray that looks like this
{
"@active" = false;
"@name" = NAME1;
},
{
"@active" = false;
"@name" = NAME2;
}
Is there a way to convert this to an NSDictionary and then use objectForKey to get an array of the name objects? How else can I get these objects?
There is a even shorter form then this proposed by Hubert
NSArray *allNames = [array valueForKey:@"name"];
valueForKey:
on NSArray returns a new array by sending valueForKey:givenKey
to all it elements.
From the docs:
valueForKey:
Returns an array containing the results of invokingvalueForKey:
usingkey
on each of the array's objects.
- (id)valueForKey:(NSString *)key
Parameters
key
The key to retrieve.Return Value
The value of the retrieved key.Discussion
The returned array containsNSNull
elements for each object that returnsnil
.
Example:
NSArray *array = @[@{ @"active": @NO,@"name": @"Alice"},
@{ @"active": @NO,@"name": @"Bob"}];
NSLog(@"%@\n%@", array, [array valueForKey:@"name"]);
result:
(
{
active = 0;
name = Alice;
},
{
active = 0;
name = Bob;
}
)
(
Alice,
Bob
)