假设您有一个自定义对象,它具有如下自定义说明:
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
您对此有任何解决方案吗?
我不想阻止您为您的类制作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
po object.customDescription as NSString