问题
Hi My NSArray contains duplicates like this(i have to delete the duplicates)
titles: Father's Day
titles: Father's Day
titles: Father's Day
titles: Election Day
titles: Election Day
titles: Election Day
titles: Easter
titles: Easter
titles: Earth Day
titles: Earth Day
titles: Earth Day
titles: Cinco de Mayo
titles: Cinco de Mayo
titles: Cinco de Mayo
titles: Christmas Eve
titles: Christmas Eve
titles: Christmas Eve
titles: Christmas titles: Christmas titles: Christmas
I have keep one name only and other duplicates are not wanted. how i have do this please guide me with bit clear explanation, to solve this issue. Thank you.
回答1:
If you care about ordering, you can create a new mutable array, loop through each object in the old array and only add it if it doesn't already exist:
NSMutableArray *uniqueItems = [NSMutableArray array];
for (id item in allItems)
if (![uniqueItems containsObject:item])
[uniqueItems addObject:item];
If not, it's much simpler to just use a set:
NSSet *uniqueItems = [NSSet setWithArray:allItems];
回答2:
Is your NSArray that you wish to dedupe already sorted? It appears so from your question. In that case, the following code would do:
NSMutableArray *uniqueItems = [NSMutableArray array];
id lastSeenUniqueObject = nil;
for (NSObject *item in allItems) {
if (![item isEqual:lastSeenUniqueObject]) {
[uniqueItems addObject:item];
lastSeenUniqueObject = item;
}
}
This has a runtime complexity of N (i.e. fast), as compared to the (approx) N^2 complexity of rpetrich's answer.
If you don't know that the Array's contents is sorted, you have two options:
A) just sort it and then apply the above algorithm, which gives n log n
runtime complexity (way better than N^2 still),
or
B) use an NSMutableSet
to track already seen objects (or any other datastructure that uses buckets and hashing). The code would be like this:
NSMutableArray *uniqueItems = [NSMutableArray array];
NSMutableSet *seenItems = [NSMutableSet set];
for (NSObject *item in allItems) {
if (![seenItems containsObject:item]) {
[uniqueItems addObject:item];
[seenItems addOBject:item];
}
}
This also gives a runtime better than N^2.
回答3:
See simple this..
NSMutableArray *dateArray = [[NSMutableArray alloc]initWithObjects:@"December 29,2010",
@"December 28,2010",
@"December 22,2010",
@"December 22,2010",
@"December 22,2010",@"December 21,2010",@"December 28,2010",nil];
for Avoid Duplicate use this...
NSSet *cleanedArray = [NSSet setWithArray:dateArray];
NSArray *array = [[NSArray alloc]initWithArray:[cleanedArray allObjects]];
for (int i=0; i<[array count]; i++) {
NSLog(@"The Given Array is %@",[array objectAtIndex:i]);
}
来源:https://stackoverflow.com/questions/5281295/iphone-sdk-how-to-delete-duplicates-in-the-nsarray