我如何最容易找到一个三维数组在Cocoa? [英] How can I most easily flatten a three-dimensional array in Cocoa?
问题描述
说我有一个这样的数组:
NSArray * threeDimensionalArray = @ [
@ [
@ [@Peter,@Paul,@Mary],@ [@Joe,@Jane]
],
@ [
@ @Alice,@Bob]
]
];
,我希望它成为:
@ [@Peter,@Paul,@Mary,@Joe,@Jane,@Alice,@Bob] $ b $我如何最容易地创建这个扁平数组? >解决方案键值编码(KVC)集合运算符 @unionOfArrays
使一级数组平坦化,因此应用它两次产生所需的结果。
集合运算符( @count
除外)需要一个集合属性的关键路径,已经是数组(因此集合)本身,关键路径必须 self
。
因此,我们需要将 @unionOfArrays
应用两次 self
键路径,产生以下KVC调用以展平3D数组:
NSArray * flattenedArray = [threeDimensionalArray valueForKeyPath:@ @ unionOfArrays.self。@ unionOfArrays.self];
Say I have an array such as this:
NSArray *threeDimensionalArray = @[
@[
@[ @"Peter", @"Paul", @"Mary" ], @[ @"Joe", @"Jane" ]
],
@[
@[ @"Alice", @"Bob" ]
]
];
and I want it to become:
@[ @"Peter", @"Paul", @"Mary", @"Joe", @"Jane", @"Alice", @"Bob" ]
How can I most easily create this flattened array?
解决方案 The key-value coding (KVC) collection operator @unionOfArrays
flattens one level of arrays, so applying it twice produces the desired result.
Collection operators (other than @count
) need a key path to a collection property, and since our objects are already arrays (and hence collections) in themselves, the key path will have to be self
.
We therefore need to apply @unionOfArrays
twice with the self
key path, yielding the following KVC call to flatten a 3D array:
NSArray *flattenedArray = [threeDimensionalArray valueForKeyPath: @"@unionOfArrays.self.@unionOfArrays.self"];
这篇关于我如何最容易找到一个三维数组在Cocoa?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!