2

I'm trying to make an array of array of strings so that I can eventually pull out something like ArrayOfArrays[0][1] = "hi".

NSString *ArrayOne[] = {@"hello", @"hi"};
NSString *ArrayTwo[] = {@"goodbye", @"bye"};

NSArray *ArrayOfArrays[] = {@[*ArrayOne, *ArrayTwo]};

However when I try to do this, I get an error: Initializer element is not a compile-time constant.

I've read that this is because I'm creating an array with dynamic values, though it should be static. Not sure how to work around this.

Any advice on making an array of array of strings?

3 Answers3

0

Use NSArray, or rather NSMutableArray if you want to modify it after creation:

NSMutableArray *arrayOne = [@[@"hello", @"hi"] mutableCopy];
NSMutableArray *arrayTwo = [@[@"goodbye", @"bye"] mutableCopy];
NSMutableArray *arrayOfArrays = [@[arrayOne, arrayTwo] mutableCopy];

There are other ways to initialise it, but this is the only way that allows you to use Objective-C literal syntax.

You cannot store plain ol' C arrays within an Objective-C collection class as your code attempts to do.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • Thanks for the advice. When I use this code, I get the same "Initializer element is not a compile-time constant" for the arrayOne and arrayTwo and "Collection element of type 'NSMutableArray' is not an Objective-C object" -- any tips? – Nadir Bilici Oct 31 '15 at 17:39
  • @NadirBilici Hmmm, I don't see why. Are you sure you've copied it exactly? – trojanfoe Oct 31 '15 at 17:40
0

You wrote:

it should be static

if this is what you want then your use of C arrays is quite valid, you just got the syntax wrong. You can use:

NSString *arrayOfArrays[][2] =
{  {@"hello", @"hi"},
   {@"goodbye", @"bye"},
};

Important: The 2 is the number of elements in the inner array, you do not change it when adding further pairs.

This will give you a compile-time static array.

If what you are making is a map from one word to another you might be better off with a dictionary, e.g.:

NSDictionary *wordMap =
   @{ @"hello" : @"hi",
      @"goodbye" : @"bye"
    };

and accessing an element becomes:

wordMap[@"hello"];

Note: the dictionary "constant" here is actually executed code; the C array version can appear as a global or local initialiser, while the dictionary initialisation must be done in a method/function - but it can assign to a global.

HTH

CRD
  • 52,522
  • 5
  • 70
  • 86
-1
NSArray *array = @[
                   @[[ @"hello", @"hi" ] mutableCopy],
                   @[[ @"goodbye", @"bye" ] mutableCopy],
                  ];

NSLog(@"%@ is short for %@", array[0][1], array[0][0]);

Output: hi is short for hello

Avi
  • 7,469
  • 2
  • 21
  • 22