How to get values from NSDictionaries inside an NSArray

▼魔方 西西 提交于 2019-12-21 07:28:09

问题


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:


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.



来源:https://stackoverflow.com/questions/12235514/how-to-get-values-from-nsdictionaries-inside-an-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!