向Xcode输出添加换行符

问题描述 投票:1回答:2

假设您有一个自定义对象,它具有如下自定义说明:

class CustomObject {

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

[在LLDB控制台中使用\n命令打印换行符po时,是否可以在控制台中使它起作用?

现在,LLDB将\n打印为文本的一部分,并且不对其进行处理:

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

期望的结果是:

po object.customDescription
> Title: Hello
  Subtitle: World

您对此有任何解决方案吗?

swift xcode lldb
2个回答
4
投票

我不想阻止您为您的类制作lldb数据格式化程序。与po相比,它们具有的优点是,它们使lldb可以向您显示数据的摘要表示,而不必在正在运行的程序中调用代码。另外,如果您使用Xcode,则Xcode本地视图将自动显示您的数据格式化程序。

但要弄清po的工作方式:

lldb po命令通过为您提供的表达式解析到的对象调用语言指定的描述方法来工作。因此,例如在您的示例中,您看到的是Swift String类的description方法的结果,该方法显示字符串的“程序员视图”。

对于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将打印debugDescription,但print将打印description

[如果您想变得更高级,或者想让po代表对象的“结构”,例如Swift数组的po结果,您可以为您的类创建自定义Mirror。这里有文档:

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

并且如果不清楚,那么可以在以下快速来源中找到Mirrors的实现:

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


4
投票
po object.customDescription as NSString
© www.soinside.com 2019 - 2024. All rights reserved.