ios 如何在 Objective-C 中组合两个数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4741646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:36:03  来源:igfitidea点击:

How would I combine two arrays in Objective-C?

iosobjective-c

提问by Moshe

What is the Objective-C equivalent of the JavaScript concat()function?

JavaScriptconcat()函数的 Objective-C 等价物是什么?

Assuming that both objects are arrays, how would you combine them?

假设两个对象都是数组,你将如何组合它们?

回答by grahamparks

NSArray's arrayByAddingObjectsFromArray:is more-or-less equivalent to JavaScript's .concat()method:

NSArray'sarrayByAddingObjectsFromArray:或多或少等价于 JavaScript 的.concat()方法:

NSArray *newArray=[firstArray arrayByAddingObjectsFromArray:secondArray];

Note: If firstArrayis nil, newArraywill be nil. This can be fixed by using the following:

注意:如果firstArray为零,newArray则为零。这可以通过使用以下方法修复:

NSArray *newArray=firstArray?[firstArray arrayByAddingObjectsFromArray:secondArray]:[[NSArray alloc] initWithArray:secondArray];

If you want to strip-out duplicates:

如果要删除重复项:

NSArray *uniqueEntries = (NSArray *)[[NSSet setWithArray:newArray] allObjects];

回答by meaning-matters

Here's a symmetric & simple way by just beginning with an empty array:

这是一种对称且简单的方法,只需从一个空数组开始:

NSArray* newArray = @[];
newArray = [newArray arrayByAddingObjectsFromArray:firstArray];
newArray = [newArray arrayByAddingObjectsFromArray:secondArray];

回答by guru

For Swift version its like charm :

对于 Swift 版本,它的魅力在于:

let a = [1,2,3]
let b = [3,4]
let c = a + b
print(c)