2
 NSLog(@"Ci sono %d categorie",category.count);
 for(int c=0; c<category.count; c++){
 CategoryArray * element =[category objectAtIndex:c];
 NSLog(@"******************************");
 NSLog(@"Titolo %@",element.label);
 NSLog(@"Source %@",element.url);
 NSLog(@"******************************");
 [element release];

This is my code! I need to remove all duplicates array... I use this code but I don't understand why it doesn't work.

uniquearray = [[NSSet setWithArray:category] allObjects];
paul_1991
  • 231
  • 1
  • 6
  • 16

5 Answers5

5

Your code does work. Try this:

NSArray *a = [NSArray arrayWithObjects:@"a", @"b", @"c", @"d", @"b", @"b", @"d", nil];
NSLog(@"a: %@\ndistinctA: %@", a, [[NSSet setWithArray:a] allObjects]);

The output is:

a: (
    a,
    b,
    c,
    d,
    b,
    b,
    d
)
distinctA: (
    c,
    d,
    a,
    b
)

Knowing that the code works for an array that contains duplicate objects, you now have to wonder why objects that you think are duplicates are not considered to be so. The existing answers regarding hash and isEqual point you in the right direction.

Caleb
  • 120,112
  • 19
  • 171
  • 259
2

Set can not contain any duplicate records. It uses a hash to tell them apart and will use isEqual if the hash is same (see the comment by Rudy Velthuis).

rckoenes
  • 68,081
  • 8
  • 130
  • 162
  • Not just a hash. It uses a hash first, ie. different hash means certainly different. But items with equal hash must be investigated further, using isEqual. – Rudy Velthuis Sep 05 '11 at 12:56
2

The elements inside this CategoryArray must correctly implement isEqual and hash for the NSSet object to be able to figure out which ones are duplicates.

You can see another SO question about overriding isEqual and hash here: Best practices for overriding isEqual: and hash

Community
  • 1
  • 1
Maurício Linhares
  • 37,947
  • 14
  • 116
  • 153
1

you can use following code.

NSMutableArray* filterResults = [[NSMutableArray alloc] init];
BOOL copy;

if (![category count] == 0) {
    for (CategoryArray *a1 in category) {
        copy = YES;
        for (CategoryArray *a2 in filterResults) {
            if ([a1.label isEqualToString:a2.label] && [a1.url isEqualToString:a2.url]) {
                copy = NO;
                break;
            }
        }
        if (copy) {
        [filterResults addObject:a1];
        }
    }
}

And you will get category array without duplicate values.
you can see Edit code. i think this will work.

Mobile App Dev
  • 1,824
  • 2
  • 20
  • 44
0

If you are worried about the order, then you can do it this way.

NSArray * newArray = [[NSOrderedSet orderedSetWithArray:oldArray] array]; // iOS 5.0 and later

keen
  • 2,851
  • 3
  • 31
  • 57