使用 NSPredicate 的不同对象
我有一个自定义对象的 NSArray。考虑自定义对象具有 PageNumber 属性。我想用“customObject.PageNumber is unique”之类的条件过滤我的 NSArray。
我知道我可以循环遍历数组并消除具有重复页码的对象。但有没有什么简单的方法可以做到呢?我已经尝试过,
[myarray valueForKeyPath:@"distinctUnionOfObjects.pageNumber"];
它给了我唯一的页码(如 7、8、9)。但我想要自定义对象本身而不仅仅是页码。任何谓词可以帮助我吗?
I have an NSArray of custom objects. Consider that the custom objects have a PageNumber property. I would like to filter my NSArray with a condition like "customObject.PageNumber is distinct".
I know I can loop through the array and eliminate object with duplicate pageNumbers. But is there any easy way to do it? I have tried,
[myarray valueForKeyPath:@"distinctUnionOfObjects.pageNumber"];
It is giving me the unique page numbers (like 7, 8, 9). But I want the custom object itself rather than just page numbers. Can any predicate help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我创建了一个简单的库,称为 Linq to ObjectiveC,它是使此类问题更容易解决的方法的集合。在您的情况下,您需要 Linq-to-ObjectiveC different 方法:
这会返回一个对象数组,每一页都有唯一的页码。
I have created a simple library, called Linq to ObjectiveC, which is a collection of methods that makes this kind of problem much easier to solve. In your case you need the Linq-to-ObjectiveC distinct method:
This returns an array of objects, each one with a unique page number.
是的,这可以在
NSPredicate
的帮助下实现。过滤后的数组是自定义对象的
NSArray
,它是使用谓词进行过滤的结果。由于您的页码是唯一的,因此它将仅返回一个对象的数组。我们通过向其传递lastObject
消息来获取该信息。参考:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/predicates.html#//apple_ref/doc/uid/TP40001798-SW1
Yes, that is possible with the help of
NSPredicate
The filtered array is an
NSArray
of your custom objects which is the result of filtering using the predicate. Since your page number is unique, it will return only an array of one object. We get that by passinglastObject
message to it.Refer:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/predicates.html#//apple_ref/doc/uid/TP40001798-SW1