OBJ-C和多维数组 [英] Obj-C and multi-dimensional arrays
问题描述
请告诉我处理的对象 - 多维数组的最佳方式?我读过的一切形式的创造NSArrays,采用C风格的数组NSArray的和STL有的甚至建议折腾和C ++风格的数组去....
Whats the best way to deal with multi-dimensional arrays in Obj-C? I've read everything form creating NSArray's of NSArrays, use C style arrays and some even suggested tossing in STL and go with c++ style arrays....
我在需要的对象的3维数组。是最好的东西NSArrays的NSArrays的NSArray的?这似乎令人费解。是否有任何对象,有可以处理n维数组在一个干净清晰的API?
I'm in the need of a 3 dimensional array of objects. Is the best thing a NSArray of NSArrays of NSArrays? That seems convoluted. Is there any object out there that can deal with n-dimensional arrays in a nice clean clear api?
一个干净,清晰的API例如:
A clean and clear api example:
obj = [MDArray getLayer: 1 atX: 10 atY: 10];
[MDArray setLayer: 1 atX: 10 atY: 10 withValue: object];
如果它的确与众不同,我的最终目标是为游戏地图数据。我已经习惯了的东西C形式,但我努力用OBJ-C(学习,我去)。
If it makes a difference, my end goal is map data for a game. I'm used to the C style of things, but am trying hard to use obj-c (learning as I go).
推荐答案
这是很自然的建议嵌套,但浪费时间,除非你需要的东西,可以做的稀疏数组。
It is natural to suggest nesting, but a waste of time unless you need something that can do sparse arrays.
一个更好的解决方案是创建一个NSMutableArray和NSNulls或NSPointerArray,它允许通过 setCount空值填充它。
法
A better solution is to create an NSMutableArray and fill it with NSNulls or an NSPointerArray, which allows for nulls via the setCount:
method.
然后,如果你需要,也就是说,能够在坐标(0..3,0..3,0..3)来处理的对象,也就是4 * 4 * 4(或64)插槽。
Then, if you need, say, to be able to handle objects at coordinates (0..3,0..3,0..3), that is 4*4*4 (or 64) slots.
从那里,把一个(X,Y,Z)坐标到阵列的时隙仅仅是一个乘法的事项; (1,2,3)在索引的对象(1 +(2×宽)+(3 *宽*高))。
From there, turning an (x,y,z) coord into a slot in the array is just a matter of multiplication; (1,2,3) is the object at index (1 + (2 * width) + (3 * width * height)).
这是数学的简单位避免了一堆额外的分配(和潜在的,你的额外拨款片段内存)。虽然我完全不prematurely优化,数学很简单,而分配的舞蹈是不是 - 这会更容易在第一时间实施
That simple bit of math avoids a bunch of extra allocations (and the potential that your extra allocations fragment memory). While I'm all for not prematurely optimizing, the math is straightforward whereas the allocation dance is not -- this'll be easier to implement in the first place.
这篇关于OBJ-C和多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!