-3

Does anyone know how I might create a constant 2d-array in iOS/Ojective-c? In java it would be

public static final String MY_2D_ARRAY = {{"dog","cat","sheep"},{"bread","end","van"}};

The following is not working for me

extern NSString * const MY_2D_ARRAY[][]; //etc
learner
  • 11,490
  • 26
  • 97
  • 169
  • @p4sh4 if it's a duplicate, do you mind writing the answer here? The link you provide does not address 2D arrays. – learner Aug 06 '14 at 04:41
  • You can see my answer below. If you can't create a single-dimensional array as a constant, you obviously cannot create a two-dimensional one. Some answers to the other question describe how you can try to use a C array to do it. – p4sh4 Aug 06 '14 at 04:43

4 Answers4

0

In Objective-C to create Array you need to use NSArray(Immutable). Alternatively NSMutableArray(mutable).

NSArray *arr = @[@[@"a", @"b"], @[@"c", @"d"]];
Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100
0

Here's how

NSArray *arr = @[
                 @[@"dog", @"cat", @"sheep"], 
                 @[@"bread", @"end", @"van"],
                  ...
                ];
Ryan
  • 4,799
  • 1
  • 29
  • 56
  • Where in the code would I put that line? Because Xcode gives the error: `Initializer element is not a compile-time constant` – learner Aug 06 '14 at 04:26
  • 1
    it would need to go inside a function that would run at the start of your app, you cant define it as an const/extern because when using the `@[]` notation, its not actually a constant, its shorthand for writing `[NSArray arrayWithObjects:x,y,z,nil];` – Fonix Aug 06 '14 at 04:32
0

You cannot create a constant NSArray, because as any Objective-C object (besides NSString), it is created at runtime and you cannot use an expression to initialise it. You should consider using some other approach, perhaps use a singleton.

p4sh4
  • 3,292
  • 1
  • 20
  • 33
-1

Since in ios you can't create constant array as you shown but you can use it as alternate

//  constants.h

+ (NSArray*) MY_2D_ARRAY;

//  constants.m

+ (NSArray*) MY_2D_ARRAY{ 

    static NSArray* arr = nil;

    if (arr == nil) {
        arr = @[@"a",@"b"]];
    }
    return arr;
}

// you can Use it where you required 

[constants MY_2D_ARRAY];

If this help you then you can accept it as solution.

Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
vnaren001
  • 244
  • 2
  • 11