字符串常量...最佳实践?
我正在寻找设置代码范围内使用的字符串常量
选项 1
的最佳实践extern const NSString *cDownloadCompleteNotification; (.h 文件)
const NSString *cDownloadCompleteNotification = @"DownloadCompleteNotification"; (.m 文件)
选项 2
定义 kNotificationDownloadComplete @"NotificationDownloadComplete" .... (common.h)
有什么好处,无论是一种方式还是另一种方式? ...或者只是个人喜好的情况?
I'm looking for a best practise of setting a code-wide used String constant
Option 1
extern const NSString *cDownloadCompleteNotification; (.h file)
const NSString *cDownloadCompleteNotification = @"DownloadCompleteNotification"; (.m file)
Option 2
define kNotificationDownloadComplete @"NotificationDownloadComplete" .... (common.h)
is there any benefit, one way or the other ? ... or just a case of personal preference ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就我个人而言,我倾向于前者,尽管它们之间没有太多选择。两种情况下的内存使用情况相同。
#define 中有一些需要注意的事情 - 例如,如果两次包含 .h 文件会怎样。
如果您使用定义,然后更改常量的值,您的某些文件可能会使用旧值进行编译,而另一些则可能会使用新值进行编译 - 您会发现找出通知处理程序没有被调用的原因非常棘手!你必须在建造之前进行清理,以确保你改变了一切。如果您使用 extern NSString,则不会发生这种情况。*
希望这有帮助。
注意,我不会将其声明为 const - 将其传递到 NSNotificationCenter 上的 postNotificationName: 方法时会收到编译器警告:(
*XCode 应该足够聪明,可以将包含 common.h 的文件标记为如果发生更改则需要重建,但我发现过去的做法是错误的。
Personally, I go for the former though there's not much to choose between them. Memory usage is the same in both cases.
There's a few things to watch out for in a #define - e.g. what if you include the .h file twice.
If you use a define and then change the constant's value some of your files might be compiled with the old value and some with the new - you would find it very tricky to work out why your notification handlers were not being called! You'd have to clean before building just to make sure that you changed everything. This won't happen if you use an extern NSString.*
Hope that's helpful.
NB I wouldn't declare it as const - you get a compiler warning when passing it into the postNotificationName: methods on NSNotificationCenter :(
*XCode should be clever enough to mark files that include common.h as needing a rebuild if it changes but I've found it to have been wrong in the past.