在工作工程中我們不必要會遇到匣掸,在數(shù)組中有重復(fù)數(shù)據(jù)的時(shí)候疗杉,如何去除重復(fù)的數(shù)據(jù)呢关噪?
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]);
方法三:利用數(shù)組的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);
打印結(jié)果:
(
"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"
)
總結(jié):這幾種方式都可以實(shí)現(xiàn)去除重復(fù)的數(shù)據(jù)拿穴,當(dāng)然也可以用for循環(huán)的方式去除方法不再敘述
削彬,這四種方法估計(jì)就夠日常用了全庸。