Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How long has NSString concatenation been supported?

I've just come across this line in some legacy code I'm editing:

[UIImage imageNamed:@"data/visuals/interface/" @"backgroundViewController"];
                                             ^^^^
                                   "Oops, what have I done here?"

I thought I must have accidentally just pasted something in the wrong place, but an undo didn't change that line. Out of curiosity, I built the program and it was successful!

Whaddyaknow? Obj-c has a more succinct way of concatenating string literals.

I added some more tests:

A simple log

NSLog(@"data/visuals/interface/" @"backgroundViewController");

data/visuals/interface/backgroundViewController

In parameters

NSURL *url = [NSURL URLWithString:@"http://" @"test.com" @"/path"];
NSLog(@"URL:%@", url);

URL:http://test.com/path

Using Variables

NSString *s = @"string1";
NSString *s2 = @"string2";

NSLog(@"%@", s s2);

Doesn't compile (not surprised by this one)

Other literals

NSNumber *number = @1 @2;

Doesn't compile


Some questions

  • Is this string concatenation documented anywhere?
  • How long has it been supported?
  • What is the underlying implementation? I expect it will be [s1 stringByAppendingString:s2]
  • Is it considered good practice by any authoritative body?
like image 627
James Webster Avatar asked Sep 07 '15 11:09

James Webster


1 Answers

This method of concatenating static NSStrings is a compile-time compiler capability that has been available for over ten years. It is usually used to allow long constant strings to be split over several lines. Similar capabilities have been available in "C" for decades.

In the C Programming Language book, 1988 second edition, page 38 describes string concatenation so it has been around for a long time.

Excerpt from the book:

String constants can be concatenated at compile time:

"hello," " world" is equivalent to "hello, world"

This is useful for spitting long strings across several source lines.

Objective-C is a strict superset of "C" so it has always supported "C" string concatenation and my guess is that because of that static NSString concatenation has always been available.

It is considered good practice when used to split a static string across several lines for readability.

like image 125
zaph Avatar answered Oct 13 '22 00:10

zaph