码迷,mamicode.com
首页 > 其他好文 > 详细

extern字符串常量,宏定义字符串常量,怎么选

时间:2015-06-12 23:44:00      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

在使用常量的时候,我看到主要有两种写法:

#define RKLICURegexEnumerationOptionsErrorKey @"RKLICURegexEnumerationOptionsErrorKey"
extern NSString * const RKLICURegexEnumerationOptionsErrorKey;

这两种写法孰优孰劣?或者在哪些情况下该用那种写法?

看了一下stackoverflow的几个答案:

http://stackoverflow.com/questions/25746/whats-the-difference-between-a-string-constant-and-a-string-literal

http://stackoverflow.com/questions/538996/constants-in-objective-c

大致是这样的:

使用#define(相当于使用@""写法的“字面量”)不能在shared libraries的情况下保证得到的字符串地址是一样的。String Programming Guide中也有描述 "The compiler makes such object constants unique on a per-module basis, and they’re never deallocated."可见使用@""的写法是在编译期就把字符串实例已经生成好的。

@""写法的字符串会在编译期被替换成NSConstantString的实例,NSString也是唯一一种可以在编译期被实例化的类。

所以在shared libraries的情况下, 如果用@""的字符串作为dictionary的key的话,会导致它需要做isEqualToString的比较,如果用extern NSString * const,只要做指针的比较。显然指针比较比逐个字符比较快多了。

所以如果需要作为dictionary的key的话,使用extern NSString * const的写法,要比@""的写法(也就是用#define)更好。

 

转:http://segmentfault.com/q/1010000000193333

 

extern字符串常量,宏定义字符串常量,怎么选

标签:

原文地址:http://www.cnblogs.com/ygm900/p/4572792.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!