根据 Objective-C 中的属性从数组中删除重复项
我有一个包含自定义对象的数组。每个数组项都有一个名为“name”的字段。现在我想根据此名称值删除重复的条目。
我应该如何实现这一目标?
I have an array with custom objects. Each array item has a field named "name". Now I want to remove duplicate entries based on this name value.
How should I go about achieving this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我不知道框架提供了任何标准方法来执行此操作。所以你必须用代码来完成。像这样的事情应该是可行的:
I do not know of any standard way to to do this provided by the frameworks. So you will have to do it in code. Something like this should be doable:
您可能必须自己编写这个过滤方法:
You might have to actually write this filtering method yourself:
我知道这是一个老问题,但还有另一种可能性,具体取决于您的需要。
苹果确实提供了一种方法来做到这一点 - 键值编码集合运算符。
对象运算符让您可以对集合进行操作。在这种情况下,您需要:
@distinctUnionOfObjects
NSArray *distinctArray = [arrayWithDuplicates
valueForKeyPath:@"@distinctUnionOfObjects.name"];
不过,在您的情况下,您需要整个对象。所以你必须做的有两件事:
1)使用
@distinctUnionOfArrays
代替。例如,如果您有来自其他集合的这些自定义对象,请使用@distinctUnionOfArray.myCollectionOfObjects2) 在这些对象上实现
isEqual:
来返回它们的 .name 是否相等I know this is an old question but here is another possibility, depending on what you need.
Apple does provide a way to do this -- Key-Value Coding Collection Operators.
Object operators let you act on a collection. In this case, you want:
@distinctUnionOfObjects
NSArray *distinctArray = [arrayWithDuplicates
valueForKeyPath:@"@distinctUnionOfObjects.name"];
In your case, though, you want the whole object. So what you'd have to do is two-fold:
1) Use
@distinctUnionOfArrays
instead. E.g. If you had these custom objects coming from other collections, use@distinctUnionOfArray.myCollectionOfObjects
2) Implement
isEqual:
on those objects to return if their .name's are equal我会为此受到批评...
你可以将数组转换成字典。不确定这有多有效,取决于实现和比较调用,但它确实使用了哈希映射。
*注意,这可能会改变数组的顺序。
I'm going to get flak for this...
You can convert your array into a dictionary. Not sure how efficient this is, depends on the implementation and comparison call, but it does use a hash map.
*Note, this may change the order of your array.
如果您希望自定义 NSObject 子类在名称相等时被视为相等,您可以实现
isEqual:
和hash
。这将允许您将对象添加到NSSet
/NSMutableSet
(一组不同的对象)。然后,您可以使用
NSSet
的sortedArrayUsingDescriptors:
方法轻松创建排序的NSArray
。MikeAsh 写了一篇关于实现自定义平等的相当扎实的文章: 周五问答 2010-06-18:实现平等和哈希
If you'd like your custom NSObject subclasses to be considered equal when their names are equal you may implement
isEqual:
andhash
. This will allow you to add of the objects to anNSSet
/NSMutableSet
(a set of distinct objects).You may then easily create a sorted
NSArray
by usingNSSet
'ssortedArrayUsingDescriptors:
method.MikeAsh wrote a pretty solid piece about implementing custom equality: Friday Q&A 2010-06-18: Implementing Equality and Hashing
如果您担心订单问题
If you are worried about the order
一行非常简单
It is quite simple in one line
实现 isEqual 以使您的对象具有可比性:
如何使用:
Implement isEqual to make your objects comparable:
How to use: