在工作的时候会遇到去除数组中重复数据的情况,如何去除重复的数据呢. 经过网上查找发现,有以下有三种方法:
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);
}
结果打印:
控制台输出
网友评论