0

I'm storing some default initializer values for my class as static class variables. Like this:

// List.h
static NSString *DEFAULT_LIST_NAME = @"Not Set";
static BOOL DEFAULT_RECURSION = NO;

I also need a static variable of type NSArray * set to an empty array. How can this be achieved? Currently I get the error:

Initializer element is not a compile-time constant

user7802048
  • 183
  • 6
  • Hi This question is similar to yours. There are different ways to do that. Maybe you want to check it: https://stackoverflow.com/questions/20544616/static-nsarray-of-strings-how-where-to-initialize-in-a-view-controller – wei Jun 18 '17 at 11:22
  • @SamB Why would I want to do so? – user7802048 Jun 18 '17 at 12:06
  • show a screenshot of your error. I don't get any compile warnings or errors in my Xcode 8 if I use static code lines above – Sam B Jun 18 '17 at 16:33

2 Answers2

1

You are getting the compile time error "Initializer element is not a compile-time constant" because the static variable's value is actually written into your executable file at compile time. So you can only use the constant values (not alloc/init which are executed at runtime). You can use any of the below option

  1. You can write static NSArray *arr = nil and use +initialize to create your array.

  2. Another options are you can use __attribute__ ((constructor))

  3. Yet another option is to switch the type of your source file from Objective-C to Objective-C++ (or rename it from .m to .mm, which has the same effect). In C++, such initializers don't need to be compile-time constant values, and the original code would work just fine

  4. Also you can use solution given Pat_Morita

Annie Gupta
  • 2,786
  • 15
  • 23
0

define a class method for this:

.m file

@implementation test
static NSArray *array; 
+ (NSArray *)array { 
    if (!array) array = [[NSArray alloc] init]; 
    return array;
 } 
@end
Pat_Morita
  • 3,355
  • 3
  • 25
  • 36