ios - 支持 NSString 连接多长时间了?

标签 ios objective-c string cocoa-touch concatenation

我刚刚在我正在编辑的一些遗留代码中遇到了这一行:

[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/

相关文章:

ios - 检查 UITextField 是否有前导空格

ios - 在 Swift 3 中配置 NSFetchedResultsController 很困难

ios - SwiftUI NavigationLink 立即加载目标 View ,无需单击

java - 将字符串数组转换为大数数组

ios - 使用 AlamoFire 在 Swift 中通过证书固定实现的 HTTPS 请求失败

ios - 自动检测AVrecorder没有声音

ios - 如何在表格 View 中创建单选按钮

iPhone Objective-C 自动发布泄露

string - 从字符串中删除前导数字

c# - Visual C# - 字符串追加到字符串无法正常工作