如何通过在Obj-C中串联字符串来创建常量NSString? [英] How to create constant NSString by concatenating strings in Obj-C?

查看:68
本文介绍了如何通过在Obj-C中串联字符串来创建常量NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过合并其他NSString实例来实例化一个常量NSString.

这是我在实现文件中正在做的事情:

static NSString *const MY_CONST = @"TEST";
static NSString *const MY_CONCATENATE_CONST = [NSString stringWithFormat:@"STRING %@", MY_CONST];

它导致以下编译错误:Initializer元素不是常量

我想这是因为stringWithFormat不会返回常量NSString,但是由于没有其他方法可以在Obj-C中连接字符串,我该怎么办?

感谢您的帮助,

埃里克.

解决方案

我认为您需要退后一步,考虑 if 是否需要将字符串定义为const.

很显然,该字符串不是常量,因为您试图为其分配新值-这是不可能的,因为您特别指示编译器使用const关键字来确保该值未更改. /p>

如果该字符串作为属性驻留在类中,则可以将其设置为只读属性-即访问器方法,但不能使用setter方法.这样一来,您就可以在类中内部构造自己的字符串,同时避免调用者更改其值.

I'm trying to instanciate a constant NSString by concatanating other NSString instances.

Here is what I'm doing in my implementation file :

static NSString *const MY_CONST = @"TEST";
static NSString *const MY_CONCATENATE_CONST = [NSString stringWithFormat:@"STRING %@", MY_CONST];

It leads to the following compilation error : Initializer element is not constant

I suppose this is because stringWithFormat doesn't return a constant NSString, but since there is no other way to concatenate strings in Obj-C, what am I supposed to do ?

Thanks for your help,

Eric.

解决方案

I think you need to step back and think about if the string needs to be defined as a const.

Clearly the string isn't a constant since you are trying to assign a new value to it - and that is not possible since you specifically instructed the compiler to make sure the value wasn't changed by using the const keyword.

If the string resides as a property in a class you could make it a read-only property - i.e. accessor method but no setter method. You would then be able to construct your string as you wish in the class internally while keeping the callers from changing the value.

这篇关于如何通过在Obj-C中串联字符串来创建常量NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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