从 NSArray 获取单个属性的 NSArray
我面临着一个非常常见的情况。
我有一个 NSArray,它有一个自定义类型的对象,比如 Person。 Person 类具有以下属性:firstName、lastName 和age。
如何从具有 Person 对象的 NSArray 中获取仅包含一个属性的 NSArray?
就像:
NSArray *people;
NSArray *firstNames = [people getArrayOfAttribute:@"firstName" andType:Person.Class]
我有一个编写 for 循环并填充 firstNames 数组的解决方案,但我不想这样做。
I am facing a very regular scenario.
I have an NSArray which has object of a custom type, say Person. The Person class has the attributes: firstName, lastName and age.
How can I get an NSArray containing only one attribute from the NSArray having Person objects?
Something like:
NSArray *people;
NSArray *firstNames = [people getArrayOfAttribute:@"firstName" andType:Person.Class]
I have a solution of writing a for loop and fill in the firstNames array but I don't want to do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
NSArray 将使用 KVC 为您处理此问题,
这将为您提供数组中每个条目的 firstName 值的数组
NSArray will handle this for you using KVC
This will give you an array of the firstName values from each entry in the array
查看 NSMutableArray 中的 filterUsingPredicate: 方法,基本上您创建了一个 NSPredicate 对象,该对象将定义如何过滤数组。
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html#//apple_ref/doc/uid/TP40001794-CJBDBHCB
本指南将为您提供概述,并有一个处理数组的部分。
Check out the filterUsingPredicate: method in NSMutableArray, basically you create a NSPredicate object that will define how the array will be filtered.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html#//apple_ref/doc/uid/TP40001794-CJBDBHCB
This guide will give you an overview, and has a section for dealing with arrays.
您还可以使用基于块的枚举:
好处是如果您有一群人,它会快速且高效......
You can also use block based enumeration:
The benefit is it is fast and efficient if you have a bunch of people...