Xcode semantic issue "Initializer element is not a compile-time constant "

I have this Error with calling NSMakeRange method. What I'm doing wrong?

#import <Foundation/Foundation.h>
//
NSRange range1 = NSMakeRange(12, 5);

Upvotes: 2

Views: 4339

Answers (2)

rakeshNS
rakeshNS

Reputation: 4257

initializer-element-is-not-a-compile-time-constant error will throw when you try to initialize an variable inside @implementation and out side any methods. You can declare variables before @implementation so that it can be accessed by every methods. And you can declare variable inside a method so that it can be visible inside that method.

Upvotes: 0

yuji
yuji

Reputation: 16725

When you initialize a variable outside of a function or method, you can only use constant values: you can't execute any code. Here the problem is that you're trying to execute NSMakeRange. (See the answers to this question, which is similar).

The solution is to declare range1 but not assign any value to it, and then implement an +initialize method that sets the value. initialize is a class method that is invoked before any other methods are called in your class.

+ (void)initialize {
    if (range1 == NULL) {
        range1 = NSMakeRange(12, 5);
    }
}

Upvotes: 5

Related Questions