如何在 Objective-C 中定义非字符串常量?
我可以像这样定义全局字符串:
// .h
extern NSString * const myString;
// .m
NSString * const myString = @"String";
现在我需要类似地定义 UIcolor,我该怎么做?
我正在尝试:
// .h
extern UIColor * const myColor;
// .m
UIColor * const myColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
但它不起作用,我收到错误:初始化器元素不是常量
谢谢
I can define global strings like this:
// .h
extern NSString * const myString;
// .m
NSString * const myString = @"String";
Now I need to define UIcolor similarly, How can I do it?
I'm trying:
// .h
extern UIColor * const myColor;
// .m
UIColor * const myColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
But it doesn't work, I'm getting error: initializer element is not constant
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能使用方法调用(或任何不是编译时常量的表达式)来初始化全局变量。它适用于您的
@"String"
示例,因为它是一个常量表达式。不需要调用任何代码来对其进行评估。You can't initialize global variables with method calls (or any expression which is not a compile time constant). It works with your
@"String"
example because that is a constant expression. No code needs to be called to evaluate it.不幸的是,字符串是一种特殊情况。对于任何其他类型的对象,您必须首先将其设置为 nil,然后在启动时提供一个值。执行此操作的一个好地方是在相关类的初始化方法中(不要与实例 init 方法混淆),该方法保证在实例化类之前至少被调用一次。 (请注意,我说“至少一次”;根据类层次结构,它可能会再次被调用,因此在为它们分配新值之前检查全局变量是否为零。)
Strings are a special case, unfortunately. For any other type of object, you will have to initially set it to nil and then provide a value on launch. A good place to do this is in a related class's initialize method (not to be confused with the instance init method), which is guaranteed to be called at least once before the class is instantiated. (Note I said "at least once"; it might be called again depending on the class hierarchy, so check if your globals are nil before you assign them new values.)
有效的一件事是:
但是,如果您只想初始化单一颜色,当然这是相当难看的。
One thing that works is:
But of course it’s quite ugly if you just want to initialize a single color.