how to remove duplicate value in NSMutableArray

这一生的挚爱 提交于 2019-12-02 05:13:29
Ankit Vyas

You can use NSSET but if you it is only used when order doesn't matter if order matter then go for this approach.I have used it and it give perfect answer. in Place of NSmutableArray array put your NSmutableArray which contains duplicate Value.

NSArray *copy = [NSmutableArray copy];

NSInteger index = [copy count] - 1;

for (id object in [copy reverseObjectEnumerator])
 {

 if ([NSmutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound)

 {
        [NSmutableArray removeObjectAtIndex:index];

 }

    index--;
}

[copy release];
Georg Schölly

You should be using an NSMutableSet in the first place.

For eliminating all double entries in an array, see this question:
Make NSMutableArray or NSMutableSet unique.

IHSAN KHAN

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..

for(int j = 0; j < [myArray count]; j++){
    for( k = j+1;k < [myArray count];k++){
        NSString *str1 = [myArray objectAtIndex:j];
        NSString *str2 = [myArray objectAtIndex:k];
        if([str1 isEqualToString:str2])
            [myArray removeObjectAtIndex:k];
       }
}
// Now print your array and 
Jules

I think its better to do this:

 NSMutableIndexSet *indexes = [[NSMutableIndexSet alloc]init];

 for(int j = 0; j < [myArray count]; j++) {

 for( k = j+1;k < [myArray count];k++) {

    NSString *str1 = [myArray objectAtIndex:j];
    NSString *str2 = [myArray objectAtIndex:k];
    if([str1 isEqualToString:str2])
        [indexes addIndex:k];
   }
}

[myArray removeObjectsAtIndexes:indexes];

You can run into problems if you manipulate the array while looping in my experience.

This is another way:

- (NSArray *)removeDuplicatesFrom:(NSArray *)array {
    NSSet *set = [NSSet setWithArray:array];
    return [set allObjects];
}

maybe you can try the NSArray category.

#import <Foundation/Foundation.h>

@interface NSArray(filterRepeat)
-(NSArray *)filterRepeat;

@end


#import "NSArray+repeat.h"
@implementation NSArray(filterRepeat)
-(NSArray *)filterRepeat
{
    NSMutableArray * resultArray =[NSMutableArray array];
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (![resultArray containsObject: obj]) {
            [resultArray addObject: obj];
        }
    }];
    return resultArray;
}
@end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!