iPhone sdk: how to delete duplicates in the NSArray

烂漫一生 提交于 2019-12-08 04:20:31

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];

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.

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]);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!