开发者

How to declare and use 3 dimensional array in ObjectiveC?

I wonder how to solve the following problem: I want to get access to one value based on a pair of values, so e.g. for values 0 and 1 I want to get 3, for 开发者_StackOverflow中文版4 and 5 I want to get 2, etc. I was thinking about declaring 3 dimensional array. Is there any better way to achieve this? If not, how can I declare 3d array in ObjectiveC?

Thanks!


If you want results based on pairs of values (rather than triples), then you want a 2D array.

Usually, 2D arrays are just arrays of arrays. If you want to use Obj-C's NSArray object, then you'd just do something like this:

NSArray* yCoord1 = [NSArray arrayWithObjects:@"oneValue", @"secondValue", nil];
NSArray* yCoord2 = [NSArray arrayWithObject:@"thirdValue"];

NSArray* array = [NSArray arrayWithObjects:yCoord1,yCoord2,nil];

Then, to access the array:

NSUInteger xCoord = 0;
NSUInteger yCoord = 1;

[[array objectAtIndex:xCoord] objectAtIndex:yCoord]; //Result: @"secondValue"

It's also possible to use plain C arrays in this way; google "2D C arrays" for tons of tutorials if you'd prefer that.


If you are going to have a value for most or every possible pair and are storing only integer values (as it seems from your example), a real C array might well meet your needs best, because you can quickly index into a 3D array to get what you are looking for.

If it's a sparse set of data, I can see something like what you are doing working out better if you concatenate your two key values together into something like "1-Firstval;2-SecondVal" and hold the numbers you are looking for in an NSDictionary. Then you still get a fast lookup without using a lot of memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜