在 Xcode 输出中添加换行符

Add line break to Xcode output

假设您有一个自定义对象,其自定义描述如下:

class CustomObject {

    var customDescription: String {
        return "Title: Hello, \n Subtitle: World"
    }
}

在 LLDB 控制台中使用 po 命令打印时,有没有办法让换行符 \n 在控制台中工作?

现在 LLDB 打印 \n 作为文本的一部分并且不处理它:

po object.customDescription
> "Title: Hello, \n Subtitle: World"

期望的结果是:

po object.customDescription
> Title: Hello
  Subtitle: World

你有什么解决办法吗?

我不想阻止您为 classes 制作 lldb 数据格式化程序。与 po 相比,它们的优势在于它们为 lldb 提供了一种向您展示数据摘要表示的方法,而无需调用 运行 程序中的代码。此外,如果您使用 Xcode,Xcode 本地视图将自动显示您的数据格式化程序。

但要弄清楚 po 的工作方式:

lldb po 命令通过为您提供的表达式解析到的对象调用语言指定的描述方法来工作。因此,例如在您的示例中,您看到了 Swift 字符串 class 的描述方法的结果,它显示了字符串的 "programmer's view"。

在 Swift 的情况下,有几种方法可以提供描述。最简单的是实现 CustomStringConvertible 协议:

class CustomObject : CustomStringConvertible {

    var description: String {
        return "Title: Hello,\n Subtitle: World"
    }
}

func main()
{
  let my_object = CustomObject()
  print (my_object)
}

main()

然后当你调试这个的时候,你会看到:

(lldb) br s -p print
Breakpoint 1: where = desc`desc.main() -> () + 27 at desc.swift:11, address = 0x000000010000116b
(lldb) run
Process 69112 launched: '/private/tmp/desc' (x86_64)
Process 69112 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
    frame #0: 0x000000010000116b desc`desc.main() -> () at desc.swift:11
   8    func main()
   9    {
   10     let my_object = CustomObject()
-> 11     print (my_object)
                 ^
   12   }
   13   
   14   main()
Target 0: (desc) stopped.
(lldb) po my_object
Title: Hello,
 Subtitle: World

(lldb) c
Process 69112 resuming
Title: Hello,
 Subtitle: World
Process 69112 exited with status = 0 (0x00000000) 

请注意,po 和 swift print 函数以相同的方式呈现您的对象。

如果您想要单独的调试和打印描述,那么您还需要实现 CustomDebugStringConvertible,这需要 debugDescription 属性。然后 po 将打印 debugDescriptionprint 将打印 description.

如果你想变得更漂亮,或者想让 po 代表对象的 "structure" 就像 Swift 数组(例如)的 po 结果那样,你可以为您的 class 定制 Mirror。这里有相关文档:

https://developer.apple.com/documentation/swift/mirror

如果不清楚,镜像的实现在 swift 来源中:

https://github.com/apple/swift/blob/master/stdlib/public/core/Mirror.swift

po object.customDescription as NSString