静态NSString用法与内联NSString常量 [英] static NSString usage vs. inline NSString constants
问题描述
在Objective-C中,我的理解是指令@foo定义了一个常量NSString。如果我在多个地方使用@foo,则引用相同的不可变NSString对象。
In Objective-C, my understanding is that the directive @"foo" defines a constant NSString. If I use @"foo" in multiple places, the same immutable NSString object is referenced.
为什么我经常看到这段代码片段(例如在UITableViewCell重用中) :
Why do I see this code snippet so often (for example in UITableViewCell reuse):
static NSString *CellId = @"CellId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:CellId];
而不仅仅是:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellId"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"CellId"];
我认为这是为了保护我免于编译器不会在标识符名称中输入拼写错误抓住。但如果是这样,我不能只是:
I assume it is to protect me from making a typo in the identifier name that the compiler wouldn't catch. But If so, couldn't I just:
#define kCellId @"CellId"
并避免静态NSString *位?或者我错过了什么?
and avoid the static NSString * bit? Or am I missing something?
推荐答案
将文字转换为常量是一种好习惯,因为:
It's good practice to turn literals into constants because:
- 它有助于避免拼写错误,就像你说的那样
- 如果你想改变常数,你只需要在一个地方改变它
我更喜欢使用 static const NSString *
static NSString * const
因为它比 #define
稍微安全一些。我倾向于避免使用预处理器,除非我真的需要它。
I prefer using static const NSString*
static NSString* const
because it's slightly safer than #define
. I tend to avoid the preprocessor unless I really need it.
这篇关于静态NSString用法与内联NSString常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!