从 NSArray 获取单个属性的 NSArray [英] Getting an NSArray of a single attribute from an NSArray

查看:14
本文介绍了从 NSArray 获取单个属性的 NSArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正面临一个非常常规的场景.

I am facing a very regular scenario.

我有一个 NSArray,它有一个自定义类型的对象,比如 Person.Person 类具有以下属性:firstName、lastName 和 age.

I have an NSArray which has object of a custom type, say Person. The Person class has the attributes: firstName, lastName and age.

如何从具有 Person 对象的 NSArray 中获取仅包含一个属性的 NSArray?

How can I get an NSArray containing only one attribute from the NSArray having Person objects?

类似:

NSArray *people;
NSArray *firstNames = [people getArrayOfAttribute:@"firstName" andType:Person.Class]

我有一个解决方案,可以编写一个 for 循环并填写 firstNames 数组,但我不想这样做.

I have a solution of writing a for loop and fill in the firstNames array but I don't want to do that.

推荐答案

NSArray 将使用 KVC 为您处理此问题

NSArray will handle this for you using KVC

NSArray *people ...;
NSArray *firstName = [people valueForKey:@"firstName"];

这将为您提供数组中每个条目的 firstName 值的数组

This will give you an array of the firstName values from each entry in the array

这篇关于从 NSArray 获取单个属性的 NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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