通过单个属性比较 NSSet
我试图确定两个 NSSet 是否“相等”,但不是 isEqualToSet 意义上的。两个集合中的项目是同一类,但不是同一对象,甚至不是同一对象的引用。不过,它们将有一个相同的属性 - 让我们称之为“名称”。
我最好的选择是比较这两组进行简单的组计数测试,然后进行更复杂的对象通过测试:在一组中的每个项目上,确保另一组中具有相同名称的项目?我希望有更简单的方法来处理这种情况。
I'm trying to determine if two NSSets are "equal" but not in the sense of isEqualToSet. Items in the two sets are the same class but are not the same object, or even references to the same object. They will have one property that is the same though - let's call it 'name'.
Is my best bet in comparing these two sets to do a simple set count test, then a more complex objectsPassingTest: on each item in one set, making sure an item with the same name is in the other set? I'm hoping that something simpler exists to handle this case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我遇到了同样的问题,但我需要同时比较多个属性(类 User 与属性 Name 和 Id)。
我通过添加一个返回 NSDictionary 以及类所需属性的方法解决了这个问题:
然后使用
valueForKey:
正如 Kevin Ballard 提到的:... 其中 userSet1 和 userSet2 是包含 User 对象的 NSSet。
I had the same problem, but I needed to compare multiple properties at the same time (class User with properties Name and Id).
I resolved this by adding a method returning an NSDictionary with the properties needed to the class:
and then using
valueForKey:
as Kevin Ballard mentioned:... where userSet1 and userSet2 were the NSSets that contained User objects.
您只需在两组上调用
valueForKey:
并比较结果即可。You could just call
valueForKey:
on both sets and compare the results.翻阅文档,似乎没有办法真正处理你的这种特殊情况。您将必须编写一些自定义代码来处理这个问题。就我个人而言,我建议使用
-sortedArrayUsingDescriptors:
然后比较数组,但这只是我的想法。您还可以枚举一组,然后使用 -filteredSetUsingPredicate: 缩小另一组的范围并获取其计数。无论您使用哪种方法,请考虑这样一个事实:它可能不会非常有效。这可能是不可避免的,但可能有比其他方法更好的方法来解决这个问题。值得深思。
Looking through the documentation, it seems that there is no way to really handle this special case of yours. You're going to have to write some custom code to handle this. Personally, I would recommend using
-sortedArrayUsingDescriptors:
and then comparing the arrays, but that's just me. You could also go enumerate through one set, then narrow down the other using-filteredSetUsingPredicate:
and get itscount
.Whichever method you use, consider the fact that its probably not going to be super efficient. This might be unavoidable, but there are probably ways to go about it that are better than others. Food for thought.