i'm scanning wifi info using NSMutableArray, but there are few duplicate values appear, so i try to use following code but still getting the duplicate values,
if([scan_networks count] > 0)
{
NSArray *uniqueNetwork = [[NSMutableArray alloc] initWithArray:[[NSSet setWithArray:scan_networks] allObjects]];
[scan_networks removeAllObjects];
NSSortDescriptor *networkName = [[[NSSortDescriptor alloc] initWithKey:@"SSID_STR" ascending:YES] autorelease];
NSArray *descriptors = [NSArray arrayWithObjects:networkName,nil];
[scan_networks addObjectsFromArray:[uniqueNetwork sortedArrayUsingDescriptors:descriptors]];
}
how this can be resolve, thanks
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];
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.
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
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