开发者

NSMutableArray remove duplicate items

 NSLog(@"Ci sono %d categorie",category.count);
 for(int c=0; c<category.count; c++){
 CategoryArray * element =[category objectAtIndex:c];
 N开发者_开发技巧SLog(@"******************************");
 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];


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.


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


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜