1

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 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!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thanks! Your answer is correct and very good, but andyvn22's answer better suits my needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.