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

3
  • Hi This question is similar to yours. There are different ways to do that. Maybe you want to check it: stackoverflow.com/questions/20544616/… Commented Jun 18, 2017 at 11:22
  • @SamB Why would I want to do so? Commented Jun 18, 2017 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 Commented Jun 18, 2017 at 16:33

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.