Search code examples
objective-ciosnsarraynsdictionary

How to get values from NSDictionaries inside an NSArray


I'd like to know if it's possible to get a values from a desired key inside an NSDictionary that is in NSArray.

Example:

NSArray *array = @[ @{@"title" : @"title 1", @"description" : @"description 1"},
@{@"title" : @"title 2", @"description" : @"description 2"}, 
@{@"title" : @"title 3", @"description" : @"description 3"} ];

I'd like to get (without creating a new NSMutableArray) all the titles inside my NSArray. Maybe I'm doing something wrong and my approach is bad altogether.

I know I could create a new class and have 2 properties (title, desc), but is there a way without creating a class or making a new NSMutableArray and iterating thorough my array?


Solution

  • Easy:

    NSArray *titles = [array valueForKey:@"title"];
    

    This works because NSArray's implementation of valueForKey: returns a new array containing the results of valueForKey: for each of the array's objects.