gpt4 book ai didi

objective-c - 如何从多个数组中提取唯一对象

转载 作者:太空狗 更新时间:2023-10-30 04:01:14 25 4
gpt4 key购买 nike

编辑:
我有两个不同的数组,其中包含一些重复的字符串,我想创建一个仅包含唯一字符串的新数组。

例如,拿这两个数组:

NSArray *array1 = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",nil]; 
NSArray *array2 = [[NSArray alloc] initWithObjects:@"a",@"d",@"c",nil];

// Result should be an array with objects "b", and "d"
// since they are the only two that are not repeated in the other array.

最佳答案

编辑:

// Your starting arrays
NSArray *array1 = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",nil];
NSArray *array2 = [[NSArray alloc] initWithObjects:@"a",@"d",@"c",nil];

// Create two new arrays that only contain the objects
// which are not in the other array:
NSMutableArray *uniqueElementsInArray1 = [array1 mutableCopy];
[uniqueElementsInArray1 removeObjectsInArray:array2];

NSMutableArray *uniqueElementsInArray2 = [array2 mutableCopy];
[uniqueElementsInArray2 removeObjectsInArray:array1];

// Combine the two arrays.
// Result contains objects @"b" and @"d":
NSArray *result = [uniqueElementsInArray1 arrayByAddingObjectsFromArray:uniqueElementsInArray2];

关于objective-c - 如何从多个数组中提取唯一对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10892026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com