Obj-C and multi-dimensional arrays
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....
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?
A clean and clear api example:
obj = [MDArray getLayer: 1 atX: 10 atY: 10];
[MDArray setLayer: 1 atX: 10 atY: 10 withValue: object];
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.
A better solution is to create an NSMutableArray and fill it with NSNulls or an NSPointerArray, which allows for nulls via the setCount:
method.
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.
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)).
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.
I would suggest, as Aurum said in the comments, writing your own multi dimensional array wrapper.
It would be relatively simple - the wrapper would own the Array of Arrays of Arrays, but expose methods like you describe which hide away the relatively ugly code of traversing the arrays.
There is no multi-dimensional array in the standard library. I would wrap the thing in my own class, it’s quite simple to do. The implementation would be nested NSArray
s or plain C arrays, if the former solution proves to be slow.
精彩评论