How to get values from NSDictionaries inside an NS

2019-04-04 13:31发布

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?

1条回答
ゆ 、 Hurt°
2楼-- · 2019-04-04 13:44

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.

查看更多
登录 后发表回答