iOS陣列去除重複的元素的4種方法
阿新 • • 發佈:2019-01-01
_sectionArray = [@"1000w",@"200w",@"500w"];
方法一、使用NSMutableDictionary的AllKeys方法
NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithCapacity:0];
for (NSString *str in _sectionArray) {
[dic setValue:str forKey:str];
}
NSLog(@"dic allKeys%@",[dic allKeys]);
結果為:
dic allKeys(
"200W",
"500w",
"1000w"
)
方法二、使用NSSet的AllObjects方法
NSSet *set = [NSSet setWithArray:_sectionArray];
NSLog(@"set allObjects%@",[set allObjects]);
結果為:
dic allKeys(
"500W",
"1000w",
"200w"
)
方法三、使用陣列的containsObject方法
NSMutableArray *listAry = [[NSMutableArray alloc]init]; for (NSString *str in _sectionArray) { if (![listAry containsObject:str]) { [listAry addObject:str]; } } NSLog(@"listAry containsObject%@",listAry);
結果為:
dic allKeys(
"1000W",
"200w",
"500w"
)
方法四、使用keyValue方法
NSMutableArray *listAry4 = [_sectionArray valueForKeyPath:@"@distinctUnionOfObjects.self"];
NSLog(@"keyValue%@",listAry4);
結果為:
dic allKeys(
"500W",
"1000w",
"200w"
)
為什麼打印出來的順序不一樣?暫時沒了解到,後面繼續學習。