Compiler error: quot;initializer element is not a compile-time constantquot;(编译器错误:“初始化器元素不是编译时常量;)
问题描述
编译此代码时,我收到错误初始化程序元素不是编译时常量".谁能解释一下为什么?
When compiling this code, I get the error "initializer element is not a compile-time constant". Can anyone explain why?
#import "PreferencesController.h"
@implementation PreferencesController
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
NSImage* imageSegment = [[NSImage alloc] initWithContentsOfFile:@"/User/asd.jpg"];//error here
推荐答案
当您在函数范围之外定义变量时,该变量的值实际上会写入您的可执行文件.这意味着您只能使用常量值.由于您在编译时不了解运行时环境的所有信息(哪些类可用,它们的结构是什么等),所以在运行时之前您无法创建目标 c 对象,但常量字符串除外,它被赋予特定的结构并保证保持这种状态.你应该做的是将变量初始化为 nil 并使用 +initialize
来创建你的图像.initialize
是一个类方法,它将在你的类上调用任何其他方法之前被调用.
When you define a variable outside the scope of a function, that variable's value is actually written into your executable file. This means you can only use a constant value. Since you don't know everything about the runtime environment at compile time (which classes are available, what is their structure, etc.), you cannot create objective c objects until runtime, with the exception of constant strings, which are given a specific structure and guaranteed to stay that way. What you should do is initialize the variable to nil and use +initialize
to create your image. initialize
is a class method which will be called before any other method is called on your class.
例子:
NSImage *imageSegment = nil;
+ (void)initialize {
if(!imageSegment)
imageSegment = [[NSImage alloc] initWithContentsOfFile:@"/User/asd.jpg"];
}
- (id)init {
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
这篇关于编译器错误:“初始化器元素不是编译时常量";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:编译器错误:“初始化器元素不是编译时常量";
基础教程推荐
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01