sic*_*ckp 42 objective-c nsstring ios
在Objective-C中,我的理解是指令@"foo"定义了一个常量NSString.如果我在多个地方使用@"foo",则引用相同的不可变NSString对象.
为什么我经常看到这段代码片段(例如在UITableViewCell重用中):
static NSString *CellId = @"CellId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:CellId];
Run Code Online (Sandbox Code Playgroud)
而不仅仅是:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellId"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"CellId"];
Run Code Online (Sandbox Code Playgroud)
我假设它是为了保护我不会在编译器无法捕获的标识符名称中输入错误.但如果是这样,我不能只是:
#define kCellId @"CellId"
Run Code Online (Sandbox Code Playgroud)
并避免静态NSString*位?或者我错过了什么?
Tom*_*ing 59
将文字转换为常量是一种很好的做法,因为:
我更喜欢使用,因为它比它更安全.我倾向于避免预处理器,除非我真的需要它.static const NSString*
static NSString* const
#define
Ale*_*ray 36
我喜欢这里的所有答案,而没有一个如何正确宣布其中的简单例子......所以......
如果你想让常量在外部可见(即"全局")....在标题中声明它...
extern NSString *const MyTypoProneString;
并在定义它.m
的文件,OUTSIDE任何@implementation
像...
NSString * const MyTypoProneString = @"iDoNtKnOwHoW2tYpE";
这就是说......如果你只是想要一个static const
即是本地的,以你的类的实现(甚至一定的方法!)......简单地声明字符串INSIDE的实现(或方法)的...
static NSString *MavisBeacon = @"She's a freakin' idiot";
编辑 虽然我确实展示了如何做到这一点 ......我还没有确信这种风格在任何方面都比更简洁,更简单,更少重复的单一声明更好,á...
#define SomeStupidString @"DefiningConstantsTwiceIsForIdiots"
Run Code Online (Sandbox Code Playgroud)
使用#define
它们......它们不那么烦人了......只是不要让预处理器 - 玩家 - 仇敌让你失望.