在工作工程中我们不必要会遇到,在数组中有重复数据的时候,如何去除重复的数据呢?
NSArray *dataArray = @[@"2014-04-01",@"2014-04-02",@"2014-04-03",
@"2014-04-01",@"2014-04-02",@"2014-04-03",
@"2014-04-01",@"2014-04-03",@"2014-04-03",
@"2014-04-01",@"2014-04-02",@"2014-04-03",
@"2014-04-01",@"2014-04-02",@"2014-04-03",
@"2014-04-01",@"2014-04-02",@"2014-04-03",
@"2014-04-04",@"2014-04-06",@"2014-04-08",
@"2014-04-05",@"2014-04-07",@"2014-04-09",];
方法一:利用NSDictionary的AllKeys(AllValues)方法
NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithCapacity:0];
for(NSString *str in dataArray)
{
[dic setValue:str forKey:str];
}
NSLog(@"%@",[dic allKeys]);
方法二:利用NSSet的AllObjects方法
NSSet *set = [NSSet setWithArray:dataArray];
NSLog(@"%@",[set allObjects]);
方法三:利用数组的containsObject来去除
NSMutableArray *listAry = [[NSMutableArray alloc]init];
for (NSString *str in dataArray) {
if (![listAry containsObject:str]) {
[listAry addObject:str];
}
}
NSLog(@"%@",listAry);
第四种方法:利用keyValue的方式
dataArray = [dataArray valueForKeyPath:@"@distinctUnionOfObjects.self"];
NSLog(@"%@",dataArray);
打印结果:
(
"2014-04-01",
"2014-04-02",
"2014-04-03",
"2014-04-04",
"2014-04-06",
"2014-04-08",
"2014-04-05",
"2014-04-07",
"2014-04-09"
)
总结:这几种方式都可以实现去除重复的数据,当然也可以用for循环的方式去除方法不再叙述
,这四种方法估计就够日常用了。