The best way to remove duplicate values (NSString
) from NSMutableArray
in Objective-C?
在Objective-C中从NSMutableArray中删除重复值(NSString)的最佳方法是什么?
Is this the easiest and right way to do it?
这是最简单和正确的方法吗?
uniquearray = [[NSSet setWithArray:yourarray] allObjects];
14 个解决方案
#1
221
Your NSSet
approach is the best if you're not worried about the order of the objects, but then again, if you're not worried about the order, then why aren't you storing them in an NSSet
to begin with?
如果不担心对象的顺序,NSSet方法是最好的,但是,如果不担心顺序,为什么不首先将它们存储在NSSet中呢?
I wrote the answer below in 2009; in 2011, Apple added NSOrderedSet
to iOS 5 and Mac OS X 10.7. What had been an algorithm is now two lines of code:
我在2009年写下了下面的答案;2011年,苹果在iOS 5和Mac OS X 10.7上添加了NSOrderedSet。以前的算法现在有两行代码:
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
If you are worried about the order and you're running on iOS 4 or earlier, loop over a copy of the array:
如果您担心顺序,并且正在运行ios4或更早的版本,请对数组的副本进行循环:
NSArray *copy = [mutableArray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator]) {
if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
[mutableArray removeObjectAtIndex:index];
}
index--;
}
[copy release];
#2
77
I know this is an old question, but there is a more elegant way to remove duplicates in a NSArray
if you don't care about the order.
我知道这是一个老问题,但是如果您不关心顺序的话,有一种更优雅的方法可以在NSArray中删除重复的内容。
If we use Object Operators from Key Value Coding we can do this:
如果我们使用对象运算符从键值编码,我们可以这样做:
uniquearray = [yourarray valueForKeyPath:@"@distinctUnionOfObjects.self"];
As AnthoPak also noted it is possible to remove duplicates based on a property. An example would be: @distinctUnionOfObjects.name
正如AnthoPak所指出的,基于属性可以删除重复的内容。例如:@distinctUnionOfObjects.name
#3
46
Yes, using NSSet is a sensible approach.
是的,使用NSSet是一种明智的方法。
To add to Jim Puls' answer, here's an alternative approach to stripping duplicates while retaining order:
为了补充Jim Puls的答案,这里有一个替代方法,可以在保持订单的同时去除重复的部分:
// Initialise a new, empty mutable array
NSMutableArray *unique = [NSMutableArray array];
for (id obj in originalArray) {
if (![unique containsObject:obj]) {
[unique addObject:obj];
}
}
It's essentially the same approach as Jim's but copies unique items to a fresh mutable array rather than deleting duplicates from the original. This makes it slightly more memory efficient in the case of a large array with lots of duplicates (no need to make a copy of the entire array), and is in my opinion a little more readable.
它本质上与Jim的方法相同,只是将惟一项复制到一个新的可变数组中,而不是从原来的数组中删除重复项。对于具有大量重复的大数组(不需要复制整个数组),这使它的内存效率稍微高一些,在我看来,它的可读性更强一些。
Note that in either case, checking to see if an item is already included in the target array (using containsObject:
in my example, or indexOfObject:inRange:
in Jim's) doesn't scale well for large arrays. Those checks run in O(N) time, meaning that if you double the size of the original array then each check will take twice as long to run. Since you're doing the check for each object in the array, you'll also be running more of those more expensive checks. The overall algorithm (both mine and Jim's) runs in O(N2) time, which gets expensive quickly as the original array grows.
注意,在这两种情况下,检查一个项目是否已经包含在目标数组中(使用containsObject:在我的例子中,或indexOfObject:inRange:在Jim的中)对于大型数组来说不太合适。这些检查在O(N)时间内运行,这意味着如果将原始数组的大小增加一倍,那么每次检查的运行时间将增加一倍。既然您正在为数组中的每个对象执行检查,那么您也将运行更多的那些更昂贵的检查。整个算法(包括我的和Jim的)在O(N2)时间内运行,随着原始数组的增长,这个算法的开销很快。
To get that down to O(N) time you could use a NSMutableSet
to store a record of items already added to the new array, since NSSet lookups are O(1) rather than O(N). In other words, checking to see whether an element is a member of an NSSet takes the same time regardless of how many elements are in the set.
要将其降低到O(N)时间,您可以使用一个nsmutable et来存储已添加到新数组的项的记录,因为NSSet查找是O(1)而不是O(N)。换句话说,检查一个元素是否为NSSet的成员将花费相同的时间,而不管集合中有多少个元素。
Code using this approach would look something like this:
使用这种方法的代码应该是这样的:
NSMutableArray *unique = [NSMutableArray array];
NSMutableSet *seen = [NSMutableSet set];
for (id obj in originalArray) {
if (![seen containsObject:obj]) {
[unique addObject:obj];
[seen addObject:obj];
}
}
This still seems a little wasteful though; we're still generating a new array when the question made clear that the original array is mutable, so we should be able to de-dupe it in place and save some memory. Something like this:
但这似乎还是有点浪费;当问题表明原始数组是可变的时,我们仍然在生成一个新的数组,因此我们应该能够在适当的地方去dupe并保存一些内存。是这样的:
NSMutableSet *seen = [NSMutableSet set];
NSUInteger i = 0;
while (i < [originalArray count]) {
id obj = [originalArray objectAtIndex:i];
if ([seen containsObject:obj]) {
[originalArray removeObjectAtIndex:i];
// NB: we *don't* increment i here; since
// we've removed the object previously at
// index i, [originalArray objectAtIndex:i]
// now points to the next object in the array.
} else {
[seen addObject:obj];
i++;
}
}
UPDATE: Yuri Niyazov pointed out that my last answer actually runs in O(N2) because removeObjectAtIndex:
probably runs in O(N) time.
更新:Yuri Niyazov指出,我最后的答案实际上是O(N2),因为removeObjectAtIndex:可能是O(N)时间。
(He says "probably" because we don't know for sure how it's implemented; but one possible implementation is that after deleting the object at index X the method then loops through every element from index X+1 to the last object in the array, moving them to the previous index. If that's the case then that is indeed O(N) performance.)
(他说“可能”是因为我们不确定它是如何实现的;但一种可能的实现是,在删除了索引X上的对象之后,该方法将所有元素从索引X+1循环到数组中的最后一个对象,并将它们移动到前一个索引。如果是这样的话,那就是O(N)性能。
So, what to do? It depends on the situation. If you've got a large array and you're only expecting a small number of duplicates then the in-place de-duplication will work just fine and save you having to build up a duplicate array. If you've got an array where you're expecting lots of duplicates then building up a separate, de-duped array is probably the best approach. The take-away here is that big-O notation only describes the characteristics of an algorithm, it won't tell you definitively which is best for any given circumstance.
那么,怎么做?这要视情况而定。如果你有一个大的数组并且你只希望有少量的重复,那么就地去重复就可以很好地工作,这样你就不必构建一个重复的数组了。如果你有一个数组,你期望有大量的重复,然后建立一个单独的,去欺骗的数组可能是最好的方法。这里的要点是,大o符号只描述了算法的特征,它不会明确地告诉你任何特定情况下的最佳状态。
#4
19
Available in OS X v10.7 and later.
可在OS X v10.7及以后使用。
If you are worried about the order,right way to do
如果你担心这个顺序,那就去做吧。
NSArray *no = [[NSOrderedSet orderedSetWithArray:originalArray]allObjects];
Here is the code of removing duplicates values from NSArray in Order.
以下是按顺序从NSArray中删除重复值的代码。
#5
19
If you are targeting iOS 5+ (what covers the whole iOS world), best use NSOrderedSet
. It removes duplicates and retains the order of your NSArray
.
如果你的目标是iOS 5+(覆盖整个iOS世界),最好使用NSOrderedSet。它删除副本并保留NSArray的顺序。
Just do
只做
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray];
You can now convert it back to a unique NSArray
现在可以将它转换回唯一的NSArray
NSArray *uniqueArray = orderedSet.array;
Or just use the orderedSet because it has the same methods like an NSArray like objectAtIndex:
, firstObject
and so on.
或者只使用orderedSet,因为它有相同的方法,比如NSArray, objectAtIndex:, firstObject等等。
A membership check with contains
is even faster on the NSOrderedSet
than it would be on an NSArray
与NSOrderedSet相比,NSArray上的成员检查速度更快
For more checkout the NSOrderedSet Reference
要查看更多NSOrderedSet引用
#6
6
need order
需要订单
NSArray *yourarray = @[@"a",@"b",@"c"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourarray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
NSLog(@"%@",arrayWithoutDuplicates);
or don't need order
或不需要订单
NSSet *set = [NSSet setWithArray:yourarray];
NSArray *arrayWithoutOrder = [set allObjects];
NSLog(@"%@",arrayWithoutOrder);
#7
3
Here i removed duplicate name values from mainArray and store result in NSMutableArray(listOfUsers)
这里,我从主数组中删除了重复的名称值,并将结果存储为NSMutableArray(listOfUsers)
for (int i=0; i<mainArray.count; i++) {
if (listOfUsers.count==0) {
[listOfUsers addObject:[mainArray objectAtIndex:i]];
}
else if ([[listOfUsers valueForKey:@"name" ] containsObject:[[mainArray objectAtIndex:i] valueForKey:@"name"]])
{
NSLog(@"Same object");
}
else
{
[listOfUsers addObject:[mainArray objectAtIndex:i]];
}
}
#8
1
Note that if you have a sorted array, you don't need to check against every other item in the array, just the last item. This should be much faster than checking against all items.
注意,如果你有一个有序数组,你不需要检查数组中的所有其他项,只是最后一个项。这应该比检查所有项要快得多。
// sortedSourceArray is the source array, already sorted
NSMutableArray *newArray = [[NSMutableArray alloc] initWithObjects:[sortedSourceArray objectAtIndex:0]];
for (int i = 1; i < [sortedSourceArray count]; i++)
{
if (![[sortedSourceArray objectAtIndex:i] isEqualToString:[sortedSourceArray objectAtIndex:(i-1)]])
{
[newArray addObject:[tempArray objectAtIndex:i]];
}
}
It looks like the NSOrderedSet
answers that are also suggested require a lot less code, but if you can't use an NSOrderedSet
for some reason, and you have a sorted array, I believe my solution would be the fastest. I'm not sure how it compares with the speed of the NSOrderedSet
solutions. Also note that my code is checking with isEqualToString:
, so the same series of letters will not appear more than once in newArray
. I'm not sure if the NSOrderedSet
solutions will remove duplicates based on value or based on memory location.
看起来NSOrderedSet的答案也需要更少的代码,但是如果由于某种原因您不能使用NSOrderedSet,并且您有一个排序数组,我相信我的解决方案将是最快的。我不确定它与NSOrderedSet解决方案的速度相比如何。还要注意,我的代码正在检查isEqualToString:,因此,相同的一系列字母在newArray中不会出现不止一次。我不确定NSOrderedSet解决方案是否会基于值或基于内存位置删除重复项。
My example assumes sortedSourceArray
contains just NSString
s, just NSMutableString
s, or a mix of the two. If sortedSourceArray
instead contains just NSNumber
s or just NSDate
s, you can replace
我的示例假设sortedSourceArray只包含nsstring、nsmutablestring或两者的混合。如果sortedSourceArray只包含nsnumber或nsdate,你可以替换。
if (![[sortedSourceArray objectAtIndex:i] isEqualToString:[sortedSourceArray objectAtIndex:(i-1)]])
with
与
if ([[sortedSourceArray objectAtIndex:i] compare:[sortedSourceArray objectAtIndex:(i-1)]] != NSOrderedSame)
and it should work perfectly. If sortedSourceArray
contains a mix of NSString
s, NSNumber
s, and/or NSDate
s, it will probably crash.
它应该是完美的。如果sortedSourceArray包含nsstring、nsnumber和/或nsdate的混合,它可能会崩溃。
#9
1
There's a KVC Object Operator that offers a more elegant solution uniquearray = [yourarray valueForKeyPath:@"@distinctUnionOfObjects.self"];
Here's an NSArray category.
有一个KVC对象操作符提供了一个更优雅的解决方案uniquearray = [yourarray valueForKeyPath:@"@distinctUnionOfObjects.self"];这里有一个NSArray类别。
#10
1
One more simple way you can try out which will not add duplicate Value before adding object in array:-
一个更简单的方法,你可以尝试不添加重复值之前添加对象在数组:-
//Assume mutableArray is allocated and initialize and contains some value
//假设分配和初始化mutableArray并包含一些值
if (![yourMutableArray containsObject:someValue])
{
[yourMutableArray addObject:someValue];
}
#11
0
Here is the code of removing duplicates values from NSMutable Array..it will work for you. myArray is your Mutable Array that you want to remove duplicates values..
这是从NSMutable数组中删除重复值的代码。它会为你工作。myArray是你想要删除重复值的可变数组。
for(int j = 0; j < [myMutableArray count]; j++){
for( k = j+1;k < [myMutableArray count];k++){
NSString *str1 = [myMutableArray objectAtIndex:j];
NSString *str2 = [myMutableArray objectAtIndex:k];
if([str1 isEqualToString:str2])
[myMutableArray removeObjectAtIndex:k];
}
} // Now print your array and will see there is no repeated value
#12
0
Using Orderedset
will do the trick. This will keep the remove duplicates from the array and maintain order which sets normally doesn't do
使用Orderedset可以达到这个目的。这将保持从数组中删除重复的内容,并保持正常情况下设置不具有的顺序
#13
0
Remove duplicate values from NSMutableArray in Objective-C
在Objective-C中删除NSMutableArray的重复值。
NSMutableArray *datelistArray = [[NSMutableArray alloc]init];
for (Student * data in fetchStudentDateArray)
{
if([datelistArray indexOfObject:data.date] == NSNotFound)
[datelistArray addObject:data.date];
}
#14
-3
just use this simple code :
只需使用这个简单的代码:
NSArray *hasDuplicates = /* (...) */;
NSArray *noDuplicates = [[NSSet setWithArray: hasDuplicates] allObjects];
since nsset doesn't allow duplicate values and all objects returns an array
因为nsset不允许重复值,所以所有对象都返回一个数组
#1
221
Your NSSet
approach is the best if you're not worried about the order of the objects, but then again, if you're not worried about the order, then why aren't you storing them in an NSSet
to begin with?
如果不担心对象的顺序,NSSet方法是最好的,但是,如果不担心顺序,为什么不首先将它们存储在NSSet中呢?
I wrote the answer below in 2009; in 2011, Apple added NSOrderedSet
to iOS 5 and Mac OS X 10.7. What had been an algorithm is now two lines of code:
我在2009年写下了下面的答案;2011年,苹果在iOS 5和Mac OS X 10.7上添加了NSOrderedSet。以前的算法现在有两行代码:
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
If you are worried about the order and you're running on iOS 4 or earlier, loop over a copy of the array:
如果您担心顺序,并且正在运行ios4或更早的版本,请对数组的副本进行循环:
NSArray *copy = [mutableArray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator]) {
if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
[mutableArray removeObjectAtIndex:index];
}
index--;
}
[copy release];
#2
77
I know this is an old question, but there is a more elegant way to remove duplicates in a NSArray
if you don't care about the order.
我知道这是一个老问题,但是如果您不关心顺序的话,有一种更优雅的方法可以在NSArray中删除重复的内容。
If we use Object Operators from Key Value Coding we can do this:
如果我们使用对象运算符从键值编码,我们可以这样做:
uniquearray = [yourarray valueForKeyPath:@"@distinctUnionOfObjects.self"];
As AnthoPak also noted it is possible to remove duplicates based on a property. An example would be: @distinctUnionOfObjects.name
正如AnthoPak所指出的,基于属性可以删除重复的内容。例如:@distinctUnionOfObjects.name
#3
46
Yes, using NSSet is a sensible approach.
是的,使用NSSet是一种明智的方法。
To add to Jim Puls' answer, here's an alternative approach to stripping duplicates while retaining order:
为了补充Jim Puls的答案,这里有一个替代方法,可以在保持订单的同时去除重复的部分:
// Initialise a new, empty mutable array
NSMutableArray *unique = [NSMutableArray array];
for (id obj in originalArray) {
if (![unique containsObject:obj]) {
[unique addObject:obj];
}
}
It's essentially the same approach as Jim's but copies unique items to a fresh mutable array rather than deleting duplicates from the original. This makes it slightly more memory efficient in the case of a large array with lots of duplicates (no need to make a copy of the entire array), and is in my opinion a little more readable.
它本质上与Jim的方法相同,只是将惟一项复制到一个新的可变数组中,而不是从原来的数组中删除重复项。对于具有大量重复的大数组(不需要复制整个数组),这使它的内存效率稍微高一些,在我看来,它的可读性更强一些。
Note that in either case, checking to see if an item is already included in the target array (using containsObject:
in my example, or indexOfObject:inRange:
in Jim's) doesn't scale well for large arrays. Those checks run in O(N) time, meaning that if you double the size of the original array then each check will take twice as long to run. Since you're doing the check for each object in the array, you'll also be running more of those more expensive checks. The overall algorithm (both mine and Jim's) runs in O(N2) time, which gets expensive quickly as the original array grows.
注意,在这两种情况下,检查一个项目是否已经包含在目标数组中(使用containsObject:在我的例子中,或indexOfObject:inRange:在Jim的中)对于大型数组来说不太合适。这些检查在O(N)时间内运行,这意味着如果将原始数组的大小增加一倍,那么每次检查的运行时间将增加一倍。既然您正在为数组中的每个对象执行检查,那么您也将运行更多的那些更昂贵的检查。整个算法(包括我的和Jim的)在O(N2)时间内运行,随着原始数组的增长,这个算法的开销很快。
To get that down to O(N) time you could use a NSMutableSet
to store a record of items already added to the new array, since NSSet lookups are O(1) rather than O(N). In other words, checking to see whether an element is a member of an NSSet takes the same time regardless of how many elements are in the set.
要将其降低到O(N)时间,您可以使用一个nsmutable et来存储已添加到新数组的项的记录,因为NSSet查找是O(1)而不是O(N)。换句话说,检查一个元素是否为NSSet的成员将花费相同的时间,而不管集合中有多少个元素。
Code using this approach would look something like this:
使用这种方法的代码应该是这样的:
NSMutableArray *unique = [NSMutableArray array];
NSMutableSet *seen = [NSMutableSet set];
for (id obj in originalArray) {
if (![seen containsObject:obj]) {
[unique addObject:obj];
[seen addObject:obj];
}
}
This still seems a little wasteful though; we're still generating a new array when the question made clear that the original array is mutable, so we should be able to de-dupe it in place and save some memory. Something like this:
但这似乎还是有点浪费;当问题表明原始数组是可变的时,我们仍然在生成一个新的数组,因此我们应该能够在适当的地方去dupe并保存一些内存。是这样的:
NSMutableSet *seen = [NSMutableSet set];
NSUInteger i = 0;
while (i < [originalArray count]) {
id obj = [originalArray objectAtIndex:i];
if ([seen containsObject:obj]) {
[originalArray removeObjectAtIndex:i];
// NB: we *don't* increment i here; since
// we've removed the object previously at
// index i, [originalArray objectAtIndex:i]
// now points to the next object in the array.
} else {
[seen addObject:obj];
i++;
}
}
UPDATE: Yuri Niyazov pointed out that my last answer actually runs in O(N2) because removeObjectAtIndex:
probably runs in O(N) time.
更新:Yuri Niyazov指出,我最后的答案实际上是O(N2),因为removeObjectAtIndex:可能是O(N)时间。
(He says "probably" because we don't know for sure how it's implemented; but one possible implementation is that after deleting the object at index X the method then loops through every element from index X+1 to the last object in the array, moving them to the previous index. If that's the case then that is indeed O(N) performance.)
(他说“可能”是因为我们不确定它是如何实现的;但一种可能的实现是,在删除了索引X上的对象之后,该方法将所有元素从索引X+1循环到数组中的最后一个对象,并将它们移动到前一个索引。如果是这样的话,那就是O(N)性能。
So, what to do? It depends on the situation. If you've got a large array and you're only expecting a small number of duplicates then the in-place de-duplication will work just fine and save you having to build up a duplicate array. If you've got an array where you're expecting lots of duplicates then building up a separate, de-duped array is probably the best approach. The take-away here is that big-O notation only describes the characteristics of an algorithm, it won't tell you definitively which is best for any given circumstance.
那么,怎么做?这要视情况而定。如果你有一个大的数组并且你只希望有少量的重复,那么就地去重复就可以很好地工作,这样你就不必构建一个重复的数组了。如果你有一个数组,你期望有大量的重复,然后建立一个单独的,去欺骗的数组可能是最好的方法。这里的要点是,大o符号只描述了算法的特征,它不会明确地告诉你任何特定情况下的最佳状态。
#4
19
Available in OS X v10.7 and later.
可在OS X v10.7及以后使用。
If you are worried about the order,right way to do
如果你担心这个顺序,那就去做吧。
NSArray *no = [[NSOrderedSet orderedSetWithArray:originalArray]allObjects];
Here is the code of removing duplicates values from NSArray in Order.
以下是按顺序从NSArray中删除重复值的代码。
#5
19
If you are targeting iOS 5+ (what covers the whole iOS world), best use NSOrderedSet
. It removes duplicates and retains the order of your NSArray
.
如果你的目标是iOS 5+(覆盖整个iOS世界),最好使用NSOrderedSet。它删除副本并保留NSArray的顺序。
Just do
只做
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray];
You can now convert it back to a unique NSArray
现在可以将它转换回唯一的NSArray
NSArray *uniqueArray = orderedSet.array;
Or just use the orderedSet because it has the same methods like an NSArray like objectAtIndex:
, firstObject
and so on.
或者只使用orderedSet,因为它有相同的方法,比如NSArray, objectAtIndex:, firstObject等等。
A membership check with contains
is even faster on the NSOrderedSet
than it would be on an NSArray
与NSOrderedSet相比,NSArray上的成员检查速度更快
For more checkout the NSOrderedSet Reference
要查看更多NSOrderedSet引用
#6
6
need order
需要订单
NSArray *yourarray = @[@"a",@"b",@"c"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourarray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
NSLog(@"%@",arrayWithoutDuplicates);
or don't need order
或不需要订单
NSSet *set = [NSSet setWithArray:yourarray];
NSArray *arrayWithoutOrder = [set allObjects];
NSLog(@"%@",arrayWithoutOrder);
#7
3
Here i removed duplicate name values from mainArray and store result in NSMutableArray(listOfUsers)
这里,我从主数组中删除了重复的名称值,并将结果存储为NSMutableArray(listOfUsers)
for (int i=0; i<mainArray.count; i++) {
if (listOfUsers.count==0) {
[listOfUsers addObject:[mainArray objectAtIndex:i]];
}
else if ([[listOfUsers valueForKey:@"name" ] containsObject:[[mainArray objectAtIndex:i] valueForKey:@"name"]])
{
NSLog(@"Same object");
}
else
{
[listOfUsers addObject:[mainArray objectAtIndex:i]];
}
}
#8
1
Note that if you have a sorted array, you don't need to check against every other item in the array, just the last item. This should be much faster than checking against all items.
注意,如果你有一个有序数组,你不需要检查数组中的所有其他项,只是最后一个项。这应该比检查所有项要快得多。
// sortedSourceArray is the source array, already sorted
NSMutableArray *newArray = [[NSMutableArray alloc] initWithObjects:[sortedSourceArray objectAtIndex:0]];
for (int i = 1; i < [sortedSourceArray count]; i++)
{
if (![[sortedSourceArray objectAtIndex:i] isEqualToString:[sortedSourceArray objectAtIndex:(i-1)]])
{
[newArray addObject:[tempArray objectAtIndex:i]];
}
}
It looks like the NSOrderedSet
answers that are also suggested require a lot less code, but if you can't use an NSOrderedSet
for some reason, and you have a sorted array, I believe my solution would be the fastest. I'm not sure how it compares with the speed of the NSOrderedSet
solutions. Also note that my code is checking with isEqualToString:
, so the same series of letters will not appear more than once in newArray
. I'm not sure if the NSOrderedSet
solutions will remove duplicates based on value or based on memory location.
看起来NSOrderedSet的答案也需要更少的代码,但是如果由于某种原因您不能使用NSOrderedSet,并且您有一个排序数组,我相信我的解决方案将是最快的。我不确定它与NSOrderedSet解决方案的速度相比如何。还要注意,我的代码正在检查isEqualToString:,因此,相同的一系列字母在newArray中不会出现不止一次。我不确定NSOrderedSet解决方案是否会基于值或基于内存位置删除重复项。
My example assumes sortedSourceArray
contains just NSString
s, just NSMutableString
s, or a mix of the two. If sortedSourceArray
instead contains just NSNumber
s or just NSDate
s, you can replace
我的示例假设sortedSourceArray只包含nsstring、nsmutablestring或两者的混合。如果sortedSourceArray只包含nsnumber或nsdate,你可以替换。
if (![[sortedSourceArray objectAtIndex:i] isEqualToString:[sortedSourceArray objectAtIndex:(i-1)]])
with
与
if ([[sortedSourceArray objectAtIndex:i] compare:[sortedSourceArray objectAtIndex:(i-1)]] != NSOrderedSame)
and it should work perfectly. If sortedSourceArray
contains a mix of NSString
s, NSNumber
s, and/or NSDate
s, it will probably crash.
它应该是完美的。如果sortedSourceArray包含nsstring、nsnumber和/或nsdate的混合,它可能会崩溃。
#9
1
There's a KVC Object Operator that offers a more elegant solution uniquearray = [yourarray valueForKeyPath:@"@distinctUnionOfObjects.self"];
Here's an NSArray category.
有一个KVC对象操作符提供了一个更优雅的解决方案uniquearray = [yourarray valueForKeyPath:@"@distinctUnionOfObjects.self"];这里有一个NSArray类别。
#10
1
One more simple way you can try out which will not add duplicate Value before adding object in array:-
一个更简单的方法,你可以尝试不添加重复值之前添加对象在数组:-
//Assume mutableArray is allocated and initialize and contains some value
//假设分配和初始化mutableArray并包含一些值
if (![yourMutableArray containsObject:someValue])
{
[yourMutableArray addObject:someValue];
}
#11
0
Here is the code of removing duplicates values from NSMutable Array..it will work for you. myArray is your Mutable Array that you want to remove duplicates values..
这是从NSMutable数组中删除重复值的代码。它会为你工作。myArray是你想要删除重复值的可变数组。
for(int j = 0; j < [myMutableArray count]; j++){
for( k = j+1;k < [myMutableArray count];k++){
NSString *str1 = [myMutableArray objectAtIndex:j];
NSString *str2 = [myMutableArray objectAtIndex:k];
if([str1 isEqualToString:str2])
[myMutableArray removeObjectAtIndex:k];
}
} // Now print your array and will see there is no repeated value
#12
0
Using Orderedset
will do the trick. This will keep the remove duplicates from the array and maintain order which sets normally doesn't do
使用Orderedset可以达到这个目的。这将保持从数组中删除重复的内容,并保持正常情况下设置不具有的顺序
#13
0
Remove duplicate values from NSMutableArray in Objective-C
在Objective-C中删除NSMutableArray的重复值。
NSMutableArray *datelistArray = [[NSMutableArray alloc]init];
for (Student * data in fetchStudentDateArray)
{
if([datelistArray indexOfObject:data.date] == NSNotFound)
[datelistArray addObject:data.date];
}
#14
-3
just use this simple code :
只需使用这个简单的代码:
NSArray *hasDuplicates = /* (...) */;
NSArray *noDuplicates = [[NSSet setWithArray: hasDuplicates] allObjects];
since nsset doesn't allow duplicate values and all objects returns an array
因为nsset不允许重复值,所以所有对象都返回一个数组