Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare an array as a constant in Objective-c?

The following code is giving me errors:

//  constants.h extern NSArray const *testArray;
//  constants.m NSArray const *testArray = [NSArray arrayWithObjects:  @"foo", @"bar", nil];

The error I get is
initializer element is not constant

Or if I take away the pointer indicator (*) I get:
statically allocated instance of Objective-C class 'NSArray'

like image 798
Andrew Avatar asked Mar 12 '10 23:03

Andrew


People also ask

How do you declare an array constant?

In C#, use readonly to declare a const array. public static readonly string[] a = { "Car", "Motorbike", "Cab" }; In readonly, you can set the value at runtime as well unlike const.

How do you declare an array in Objective C?

To declare an array in Objective-C, we use the following syntax. type arrayName [ arraySize ]; type defines the data type of the array elements. type can be any valid Objective-C data type.

Is array a constant in C?

it's a constant array of integers i.e. the address which z points to is always constant and can never change, but the elements of z can change.


1 Answers

In short, you can't. Objective-C objects are, with the exception of NSString, only ever created at runtime. Thus, you can't use an expression to initialize them.

There are a handful of approaches.

(1) Declare NSArray *testArray without the const keyword and then have a bit of code that sets up the value that is invoked very early during application lifecycle.

(2) Declare a convenient class method that returns the array, then use a static NSArray *myArray within that method and treat it as a singleton (search SO for "objective-c singleton" for about a zillion answers on how to instantiate).

like image 90
bbum Avatar answered Oct 21 '22 02:10

bbum