编译器错误:“初始化器元素不是编译时常量” [英] Compiler error: "initializer element is not a compile-time constant"

查看:1139
本文介绍了编译器错误:“初始化器元素不是编译时常量”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译此代码时,我得到错误initializer元素不是编译时常量。谁能解释为什么?

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.

示例: / p>

Example:

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

这篇关于编译器错误:“初始化器元素不是编译时常量”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆