从 NSMutableArray 中删除重复项 [英] Removing duplicates from NSMutableArray

查看:36
本文介绍了从 NSMutableArray 中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从数组中删除重复对象时遇到了这个问题.我已经尝试过这些:

I have this problem with removing duplicate objects from an array. I tried these already:

noDuplicates = _personalHistory.personalHistory;

for (int i=[noDuplicates count]-1; i>0; i--) {
    if ([noDuplicates indexOfObject: [noDuplicates objectAtIndex: i]]<i)
        [noDuplicates removeObjectAtIndex: i];
}


for (PersonalHistory_artikels *e in _personalHistory.personalHistory) {
    if (![noDuplicates containsObject:e]) {
        NSLog(@"Dubplicates");
        [noDuplicates addObject:e];
    }
}


for (i=0; i<_personalHistory.personalHistory.count; i++) {
    PersonalHistory_artikels *test = [_personalHistory.personalHistory objectAtIndex:i];
    for (j=0; j<_personalHistory.personalHistory.count; j++) {
        PersonalHistory_artikels *test2 = [_personalHistory.personalHistory objectAtIndex:j];
        if (! [test.nieuwsTITLE_personal isEqual:test2.nieuwsTITLE_personal]) {
            NSLog(@"Add test = %@", test.nieuwsTITLE_personal);
            [noDuplicates addObject:test];
        }
    }
}

但以上都没有给我正确的数组.最后一个是最好的,但它仍然显示重复值.有人可以帮我解决这个问题吗?非常感谢你.

But none of the above gave me the right array. The last one was the best, but it still showed duplicate values. Can someone help me with this problem? Thank you very much.

推荐答案

只需将数组转换为 NSSet 并再次返回即可.一个集合不能有重复的设计.

Just convert the array to an NSSet and back again. A set can't have duplicates by design.

请注意,集合没有排序顺序.因此,您可以更便宜地放弃订单,或者进行稍贵的操作但保留订单.

Note that a set doesn't have a sorting order. Therefore, you can go cheaper and forgo the order, or go for a slightly more expensive operation but keep the order.

NSArray *hasDuplicates = /* (...) */;
NSArray *noDuplicates = [[NSSet setWithArray: hasDuplicates] allObjects];

这篇关于从 NSMutableArray 中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆