欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS去除数组中重复数据的几种方法

程序员文章站 2022-06-11 11:34:59
...

####第一种:利用NSDictionary的AllKeys(AllValues)方法

NSArray *dataArray = @[@1, @2, @3, @4, @1, @2, @5, @6, @7, @8, @9, @1, @3];
NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithCapacity:0];
for(NSString *str in dataArray)
{
    [dic setValue:str forKey:str];
}
NSLog(@"DIC %@",[dic allKeys]);
复制代码
打印结果:

DIC (
    9,
    5,
    1,
    6,
    2,
    7,
    3,
    8,
    4
)

复制代码

####第二种方法:利用NSSet的AllObjects方法

NSArray *dataArray = @[@1, @2, @3, @4, @1, @2, @5, @6, @7, @8, @9, @1, @3];
NSSet *set = [NSSet setWithArray:dataArray];
NSLog(@"SET = %@",[set allObjects]);
复制代码
SET = (
    9,
    7,
    5,
    3,
    1,
    8,
    6,
    4,
    2
)

复制代码

###第三种方法,利用数组的containsObject来去除 NSArray *dataArray = @[@1, @2, @3, @4, @1, @2, @5, @6, @7, @8, @9, @1, @3]; NSMutableArray *listAry = [[NSMutableArray alloc]init]; for (NSString *str in dataArray) { if (![listAry containsObject:str]) { [listAry addObject:str]; } } NSLog(@"CONTAINS %@",listAry);

打印结果:

CONTAINS (
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9
)

复制代码

####第四种方法:利用keyValue的方式(自己不是太明白)

 NSArray *dataArray = @[@1, @2, @3, @4, @1, @2, @5, @6, @7, @8, @9, @1, @3];

 NSArray *array1 = [dataArray valueForKeyPath:@"@distinctUnionOfObjects.self"];
 NSLog(@"DISTINC %@",array1);
复制代码
打印结果
DISTINC (
    9,
    7,
    5,
    3,
    1,
    8,
    6,
    4,
    2
)

复制代码

第五种 : NSOrderedSet去除

NSArray *dataArray = @[@1, @2, @3, @4, @1, @2, @5, @6, @7, @8, @9, @1, @3];
NSOrderedSet *orderSet = [NSOrderedSet orderedSetWithArray:dataArray];
    
NSArray *newArray = orderSet.array;
    
NSLog(@"ORDERSET %@",newArray);

复制代码
打印结果
ORDERSET (
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9
)

复制代码