根据另一个数组中对象的属性创建一个数组 [英] Creating an array from properties of objects in another array

查看:167
本文介绍了根据另一个数组中对象的属性创建一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方便的方法来获取对象的数组/集合并创建一个包含第一个数组中每个项目的某些属性的新数组/集合?

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?

例如,一个数组包含Car对象.我需要一个licensePlates数组,其中每辆车都有一个NSObject car.licensePlate.

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

目前,我只是遍历第一个将对象添加到可变结果数组中的数组,但是想知道是否存在一种实例化方法(请检查NSArray文档).

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).

推荐答案

这将返回一个数组,其中包含myCars数组中每个项目的licensePlate值:

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.

这篇关于根据另一个数组中对象的属性创建一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆