views:

1246

answers:

4

The following code is giving me errors:

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

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'

+1  A: 

See this SO question

Griffo
+2  A: 

Instances of NSArray are immutable in Objective-C, so there's no need to use the const qualifier. In fact, you would have to create an instance of NSMutableArray if you did want to be able to modify the array.

jlehr
Thanks, that makes sense. But if I remove the `const` qualifier i still get the `initializer element is not constant`. I'm sure I'm just missing something in syntax?
Andrew
Oops, didn't read your initial posting carefully. As bbum point out, objects can only be created dynamically (i.e., allocated on the heap), so we can't initialize a static variable of type NSArray. However, if all you need is an array of NSString instances, you can statically initialize a C array of strings like this: static const NSString *strings[] = { @"foo", @"bar", @"baz" };And then later use it to initialize an NSArray like so: NSString *myStrings = [NSArray arrayWithObjects:strings count:3];as bbum suggests, in a class method.
jlehr
+3  A: 

In short, you can't. Objective-C objects are, with the exception of NSString constants, only ever created at runtime and, 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 class method on some 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).

bbum
A: 
[NSArray arrayWithObjects:  @"foo", @"bar"];

should be

[NSArray arrayWithObjects:  @"foo", @"bar", nil];
guga