问题
I have this Error with calling NSMakeRange method. What I'm doing wrong?
#import <Foundation/Foundation.h>
//
NSRange range1 = NSMakeRange(12, 5);
回答1:
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);
}
}
回答2:
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.
来源:https://stackoverflow.com/questions/9860360/xcode-semantic-issue-initializer-element-is-not-a-compile-time-constant