带有自定义对象的 NSPredicates
我有以下问题,我不知道如何解决它。我有一个 NSSet,其中包含 Person 对象(带有 2 个键的 NSDictionary:姓名、年龄)。有时我会得到一个 Person 对象的 NSArray,我想将它们添加到我的 NSSet 中,但我想过滤掉重复项。我想我可以使用 NSPredicates,但我正在阅读文档,但我不明白应该如何格式化 NSPredicate 以根据 NSSet 中已有的内容过滤出数组内容。
所以我有一个包含 5 个自定义对象的 NSSet,我得到一个包含 6 个对象的 NSArray,但其中 3 个已经存在于 NSSet 中,我想将它们过滤掉。我了解应该如何处理字符串、整数等基本对象,但我不知道如何扩展它以处理自定义的更复杂的对象。
我希望我对我的问题足够清楚。非常感谢任何起点、示例或建议。
谢谢你!
I have the following problem and I cannot figure out how to solve it. I have an NSSet which contains Person objects (NSDictionary with 2 keys: name, age). From time to time I get an NSArray of Person objects and I want to add them to my NSSet but I want to filter out the duplicates. I'm thinking I could use NSPredicates but I am reading the documentation and I can't understand how should I format my NSPredicate to filter out my array content based on what I already have in NSSet.
So I have an NSSet with 5 custom objects and I get an NSArray with 6 objects but 3 of them already exist in NSSet and I want to filter them out. I understand what I should do with basic objects like Strings, integers, etc but I don't know how to extend this to work with custom more complex objects.
I hope I was clear enough with my problem. Any starting point, example or advice is much appreciated.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您已经有一个可变集,那么您实际上不需要做任何特别的事情。如果您在将来的某个时刻返回相同的 Person 实例,addObject: 将简单地忽略它。如果你对“相等”有不同的含义,而不仅仅是两个对象是否是同一个实例,那么你必须自己处理这个问题,但是如果你的新对象为 isEqual: 返回 YES ,那么当你将其放入集合中。
If you already have a mutable set, you don't really have to do anything special. If you get the same Person instance back at some point in the future, addObject: will simply ignore it. If you have a different meaning of "equality" than just whether two objects are the same instance, then you have to deal with that yourself, but if your new object returns YES for isEqual: then addObject: will already ignore it as well when you place it in the set.