说明:本文只针对少量数据的排重的几种简单方案,暂不涉及海量数据.
简单结构的排重对象
1.利用 NSArray 的 containsObject 方法
NSMutableArray *arr = [NSMutableArray array];
for (NSNumber *object in self.originArr) {
if (![arr containsObject:object]) {
[arr addObject:object];
}
}
self.originArr = [NSArray arrayWithArray:arr];
2.利用 NSDictionary 的 allValues 方法
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
for (NSNumber *object in self.originArr) {
[dic setObject:object forKey:object];
}
NSArray *arr = [dic allValues];
self.originArr = [NSArray arrayWithArray:arr];
3.利用 NSSet 的 allObjects 方法
NSSet *set = [NSSet setWithArray:self.originArr];
NSArray *arr = [set allObjects];
self.originArr = [NSArray arrayWithArray:arr];
4.利用 KVC 的 valueForKeyPath 方法
NSArray *arr = [self.originArr valueForKeyPath:@"@distinctUnionOfObjects.self"];
self.originArr = [NSArray arrayWithArray:array];
5.正常排重,不打乱数组元素的顺序
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (int i = 0; i < self.originArr.count; i++){
if ([arr containsObject:[self.originArr objectAtIndex:i]] == NO){
[arr addObject:[self.originArr objectAtIndex:i]];
}
}
self.originArr = [NSArray arrayWithArray:arr];
复杂结构的排重对象可以通过特征值(id/createTime 等)排重
NSArray *array = @[@{@"name": @"iPhone5",
@"id": @(001)
},
@{@"name": @"iPhone5s",
@"id": @(001)
},
@{@"name": @"iPhoneSE",
@"id": @(002)
},
@{@"name": @"iPhone6",
@"id": @(003)
},
@{@"name": @"iPhone6",
@"id": @(003)
},
@{@"name": @"iPhone6s",
@"id": @(004)
},
@{@"name": @"iPhone7",
@"id": @(005)
},
@{@"name": @"iPadMini",
@"id": @(006)
},
@{@"name": @"iPhone8",
@"id": @(007)
},
];
NSMutableArray *arr = [NSMutableArray array];
for (NSDictionary *dic in array) {
ProductModel *model = [ProductModel mj_objectWithKeyValues:dic];
[arr addObject:model];
}
self.originArr = [NSArray arrayWithArray:arr];
通过特征值 id 排重
NSMutableDictionary *flagDic = [NSMutableDictionary dictionary];
for (ProductModel *model in self.originArr) {
[flagDic setObject:model forKey:[NSString stringWithFormat:@"%@", model.id]];
}
self.originArr = [NSArray arrayWithArray:arr];
通过BOOL值标记
_peripheral = peripheral;
BOOL replace = NO;
// Match if we have this device from before
for (int i=0; i < _dataArr.count; i++) {
Peripheral *p = [_dataArr objectAtIndex:i];
if ([p isEqual:peripheral]) {
[_dataArr replaceObjectAtIndex:i withObject:peripheral];
replace = YES;
}
}