美文网首页
iOS开发 - NSArray 去除重复数据的方法

iOS开发 - NSArray 去除重复数据的方法

作者: Clover_B | 来源:发表于2017-05-26 13:33 被阅读716次

在工作的时候会遇到去除数组中重复数据的情况,如何去除重复的数据呢. 经过网上查找发现,有以下有三种方法:

1.containsObject方法####
- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *array = @[@"111",@"222",@"333",@"222",@"111",@"555"];
    
    [self removeRepeatWithContainObjFunc:array];
    [self removeRepeatWithDicFunc:array];
    [self removeRepeatWithNSSetFunc:array];
}

#pragma mark - containsObject方法
- (void)removeRepeatWithContainObjFunc:(NSArray *)array {
    NSMutableArray *listArray = [NSMutableArray array];
    
    for (NSString  *str in array) {
        if (![listArray containsObject:str]) {
            [listArray addObject:str];
        }
    }
    
    NSLog(@"containFunc ====  %@", listArray);
}

2.dictionary 方法#####
#pragma mark - dictionary方法
- (void)removeRepeatWithDicFunc:(NSArray *)array {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    for (NSString *str in array) {
        [dic setObject:str forKey:str];
    }
    NSLog(@"dicFunc ===== %@", [dic allKeys]);
}
3.set 方法#####
#pragma mark - set方法
- (void)removeRepeatWithNSSetFunc:(NSArray *)array {
    NSMutableSet *set = [NSMutableSet set];
    for (NSString *str in array) {
        [set addObject:str];
    }
    NSLog(@"setFunc ===== %@", set);
}

结果打印:

控制台输出

相关文章

网友评论

      本文标题:iOS开发 - NSArray 去除重复数据的方法

      本文链接:https://www.haomeiwen.com/subject/niotfxtx.html