什么时候使用静态字符串vs. #define [英] When to use static string vs. #define

查看:134
本文介绍了什么时候使用静态字符串vs. #define的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑,因为什么时候最好使用:

  static NSString * AppQuitGracefullyKey = @AppQuitGracefully; 

而不是

  #define AppQuitGracefullyKey @AppQuitGracefully

或C ++,我认为这里不同的是,这是专门为Objective C,利用一个对象,在像iPhone的设备,可能有堆栈,代码空间或内存问题,我还没有抓住。 p>

一种用法是:

  appQuitGracefully = [[NSUserDefaults standardUserDefaults] integerForKey :AppQuitGracefullyKey]; 

还是只是风格问题?



感谢。

解决方案

如果使用静态,编译器将会在二进制文件中嵌入一个字符串的副本只是传递指向那个字符串的指针,导致更紧凑的二进制文件。如果使用#define,每次使用时都会有一个单独的字符串副本存储在源代码中。常量字符串合并将处理很多重复,但是你使链接器工作更难,没有理由。


I am a little confused as to when it's best to use:

static NSString *AppQuitGracefullyKey = @"AppQuitGracefully";

instead of

#define AppQuitGracefullyKey    @"AppQuitGracefully"

I've seen questions like this for C or C++, and I think what's different here is that this is specifically for Objective C, utilizing an object, and on a device like the iPhone, there may be stack, code space or memory issues that I don't yet grasp.

One usage would be:

appQuitGracefully =  [[NSUserDefaults standardUserDefaults] integerForKey: AppQuitGracefullyKey];

Or it is just a matter of style?

Thanks.

解决方案

If you use a static, the compiler will embed exactly one copy of the string in your binary and just pass pointers to that string around, resulting in more compact binaries. If you use a #define, there will be a separate copy of the string stored in the source on each use. Constant string coalescing will handle many of the dups but you're making the linker work harder for no reason.

这篇关于什么时候使用静态字符串vs. #define的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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