Jam*_*ter 10 string cocoa-touch concatenation objective-c ios
我刚刚在编辑的一些遗留代码中看到了这一行:
[UIImage imageNamed:@"data/visuals/interface/" @"backgroundViewController"];
^^^^
"Oops, what have I done here?"
Run Code Online (Sandbox Code Playgroud)
我以为我一定是偶然地把东西贴在错误的地方,但撤消并没有改变那条线.出于好奇,我建立了程序,它成功了!
Whaddyaknow?Obj-c有一种更简洁的串联字符串文字方式.
我添加了一些测试:
一个简单的日志
NSLog(@"data/visuals/interface/" @"backgroundViewController");
Run Code Online (Sandbox Code Playgroud)
数据/视觉/接口/ backgroundViewController
在参数中
NSURL *url = [NSURL URLWithString:@"http://" @"test.com" @"/path"];
NSLog(@"URL:%@", url);
Run Code Online (Sandbox Code Playgroud)
网址:HTTP://test.com/path
使用变量
NSString *s = @"string1";
NSString *s2 = @"string2";
NSLog(@"%@", s s2);
Run Code Online (Sandbox Code Playgroud)
不编译(对此不感到惊讶)
其他文字
NSNumber *number = @1 @2;
Run Code Online (Sandbox Code Playgroud)
不编译
一些问题
[s1 stringByAppendingString:s2]这种连接静态的方法NSStrings是一种编译时编译器功能,已经存在十多年了。它通常用于允许将长常量字符串拆分为几行。几十年来,“C”中已经提供了类似的功能。
在《C 编程语言》一书中,1988 年第二版,第 38 页描述了字符串连接,因此它已经存在很长时间了。
书中摘录:
字符串常量可以在编译时连接:
"hello," " world" is equivalent to "hello, world"
Run Code Online (Sandbox Code Playgroud)
这对于跨多个源代码行吐出长字符串非常有用。
Objective-C 是“C”的严格超集,因此它始终支持“C”字符串连接,我的猜测是因为该静态NSString连接始终可用。
当用于将静态字符串拆分为几行以提高可读性时,这被认为是良好的做法。