问题描述
我正面临一个非常常规的场景.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!