iosobjective-cnsstring

Static NSString usage vs. inline NSString constants


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.

Why do I see the following 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];

Instead of just:

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 use

#define kCellId @"CellId"

and avoid the static NSString * bit? Or am I missing something?


Solution

  • It's good practice to turn literals into constants because:

    1. It helps avoid typos, like you said
    2. If you want to change the constant, you only have to change it in one place

    I prefer using static NSString* const, because it's slightly safer than #define. I tend to avoid the preprocessor unless I really need it.