我刚刚在我正在编辑的一些遗留代码中遇到了这一行:
[UIImage imageNamed:@"data/visuals/interface/" @"backgroundViewController"];
^^^^
"Oops, what have I done here?"
我想我一定是不小心把东西粘贴到了错误的地方,但是撤消并没有改变那一行。出于好奇,我构建了程序并且成功了!
你知道吗? Obj-c 有一种更简洁的连接字符串文字的方法。
我添加了更多测试:
一个简单的日志
NSLog(@"data/visuals/interface/" @"backgroundViewController");
data/visuals/interface/backgroundViewController
在参数中
NSURL *url = [NSURL URLWithString:@"http://" @"test.com" @"/path"];
NSLog(@"URL:%@", url);
URL:http://test.com/path
使用变量
NSString *s = @"string1";
NSString *s2 = @"string2";
NSLog(@"%@", s s2);
Doesn't compile (not surprised by this one)
其他文字
NSNumber *number = @1 @2;
Doesn't compile
一些问题
- 是否在任何地方记录了此字符串连接?
- 支持了多长时间?
- 底层实现是什么?我希望它将是
[s1 stringByAppendingString:s2]
- 它是否被任何权威机构视为良好做法?
最佳答案
这种连接静态 NSStrings
的方法是一种编译时编译器功能,已经存在了十多年。它通常用于允许将长常量字符串拆分为多行。几十年来,“C”中已经提供了类似的功能。
C Programming Language 一书,1988 年第二版,第 38 页描述了字符串连接,因此它已经存在了很长时间。
摘自本书:
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 是“C”的严格超集,因此它始终支持“C”字符串连接,我的猜测是因为静态 NSString
连接始终可用。
为了提高可读性,将静态字符串拆分成多行被认为是一种很好的做法。
关于ios - 支持 NSString 连接多长时间了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32437259/