Creating an array from properties of objects in another array

限于喜欢 提交于 2019-12-03 00:45:46

问题


Is there any convenient way to take an array/set of objects and create a new array/set containing some property of each item in the first array?

For example, an array contains Car objects. I need an array of licensePlates, where each car has an NSObject car.licensePlate.

Currently I just iterate through the first array adding objects to my mutable results array, but was wondering if there is an instantiation method that exists for this (checked the docs for NSArray).


回答1:


This will return an array containing the value of licensePlate from each item in the myCars array:

NSArray *licensePlates = [myCars valueForKeyPath:@"licensePlate"]

If you want only unique items (for example), you can do something like this:

NSArray *licensePlates = [myCars valueForKeyPath:@"@distinctUnionOfObjects.licensePlate"];

For more possibilities, see the Collection Operators documentation in the Key-Value Coding Programming Guide.



来源:https://stackoverflow.com/questions/9890848/creating-an-array-from-properties-of-objects-in-another-array

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