从另一个数组中对象的属性创建一个数组

时间:2022-09-25 08:03:01

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.

例如,数组包含汽车对象。我需要一系列的车牌,每辆车都有一个NSObject - ject - 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).

目前,我只是在第一个数组中迭代,向我的可变结果数组中添加对象,但是我想知道是否存在为此而存在的实例化方法(检查NSArray的文档)。

1 个解决方案

#1


115  

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

这将返回一个数组,该数组包含myCars数组中每一项的被许可证号的值:

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.

有关更多的可能性,请参阅关键值编码编程指南中的集合操作符文档。

#1


115  

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

这将返回一个数组,该数组包含myCars数组中每一项的被许可证号的值:

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.

有关更多的可能性,请参阅关键值编码编程指南中的集合操作符文档。