如何制作 NSString 宏?
如何制作一个表示常量 NSString 值的宏?我得到了 在 Xcode 4 中定义时出现“多字符字符常量”和“字符常量对其类型而言太长”警告:
#define LEVELTYPEGLASS @"Glass"
我需要转义某些内容吗?
How to make a macro that represents a constant NSString value? I'm getting
"Multi-character character constant" and "Character constant too long for its type" warnings when defining in Xcode 4:
#define LEVELTYPEGLASS @"Glass"
Do I need to escape something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
避免使用字符串常量的定义。在头文件中定义为 extern,如下所示:
并且它们在任何实现文件中实现:
这提供了更多的字符可供键入,但增加了许多好处,例如更好地为 Xcode 键入,保证对象标识(没有重复的字符串)。苹果就是这么做的,如果它对他们来说足够好,那么对你也应该有好处。
Avoid using defines for string constants. Define as an extern in the header file like this:
And them implement in any implementation file:
This gives a few more characters to type, but adds allot of benefits like better typing for Xcode, guaranteed object identity (no duplicate strings). This is how Apple do it, if its good enough for them, it should be good for you.
PeyloW 建议的解决方案很棒。但我只想指出,在将 #import "Foundation/Foundation.h" 添加到头文件后,我得到了解决方案。因此,头文件 Constants.h 应该如下所示:
然后,实现文件如下所示:
如果需要将其包含到整个项目中,则需要将其导入到 -Prefix.pch 文件中:
在这种情况下,所有宏定义都位于Constants.h 头文件和一些 NSString 常量驻留在 Constants.m 实现文件中。再次感谢 PeyloW :)
The solution suggested by PeyloW is great. But I just want to note that I got the solution working after I have added #import "Foundation/Foundation.h" to header file. So the header file Constants.h should look like:
Then, implementation file looks like:
And if you need to include that into whole project you need to import that in -Prefix.pch file:
In that case, all the macro definitions resides in Constants.h header file, and some NSString constants resides in Constants.m implementation file. Again, thanks to PeyloW :)