Getting an NSArray of a single attribute from an NSArray(从 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 NSArray 获取单个属性的 NSArray
基础教程推荐
- 如何比较两个 NSDate:哪个是最近的? 2022-01-01
- Play 商店的设备兼容性问题 2022-01-01
- SwiftUI-ScrollViewReader的ScrollTo不滚动 2022-01-01
- 为什么姜饼模拟器方向卡在应用程序中? 2022-01-01
- 如何将图像从一项活动发送到另一项活动? 2022-01-01
- navigationItem.backBarButtonItem 不工作?为什么上一个菜单仍然显示为按钮? 2022-01-01
- Android Volley - 如何动画图像加载? 2022-01-01
- UIImage 在开始时不适合 UIScrollView 2022-01-01
- Xcode UIView.init(frame:) 只能在主线程中使用 2022-01-01
- iOS - UINavigationController 添加多个正确的项目? 2022-01-01
