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

僤鯓⒐⒋嵵緔 提交于 2019-12-06 07:26:53
yuji

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);
    }
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!