如何在 NSSet 或 NSArray 中搜索具有特定属性的特定值的对象?
如何在 NSSet 或 NSArray 中搜索具有特定属性的特定值的对象?
示例:我有一个包含 20 个对象的 NSSet,每个对象都有一个 type
属性。我想获取第一个具有 [theObject.type isEqualToString:@"standard"]
的对象。
我记得可以以某种方式使用谓词来处理这类事情,对吧?
How to search an NSSet or NSArray for an object which has an specific value for an specific property?
Example: I have an NSSet with 20 objects, and every object has an type
property. I want to get the first object which has [theObject.type isEqualToString:@"standard"]
.
I remember that it was possible to use predicates somehow for this kind of stuff, right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
注意:NSSet 中第一个找到的对象的概念没有意义,因为集合中对象的顺序是未定义的。
NB: The notion of the first found object in an NSSet makes no sense since the order of the objects in a set is undefined.
您可以按照 Jason 和 Ole 的描述获取过滤后的数组,但由于您只需要一个对象,因此我会使用
-indexOfObjectPassingTest:
(如果它在数组中)或-objectPassingTest:< /code> (如果它在一个集合中)并避免创建第二个数组。
You can get the filtered array as Jason and Ole have described, but since you just want one object, I'd use
- indexOfObjectPassingTest:
(if it's in an array) or-objectPassingTest:
(if it's in a set) and avoid creating the second array.一般来说,我使用
indexOfObjectPassingTest:
因为我发现用 Objective-C 代码而不是NSPredicate
语法来表达我的测试更方便。这是一个简单的示例(想象一下integerValue
实际上是一个属性):此代码的输出是:
Generally, I use
indexOfObjectPassingTest:
as I find it more convenient to express my test in Objective-C code rather thanNSPredicate
syntax. Here's a simple example (imagine thatintegerValue
was actually a property):The output of this code is: