在Xcode输出中添加换行符

时间:2017-08-15 13:18:00

标签: swift xcode lldb

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

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

你有解决方法吗?

2 个答案:

答案 0 :(得分:3)

我不想阻止你为你的类制作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 Arrays(例如)的po结果一样,你可以自定义{{1}为你的班级。这里有文档:

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

如果不清楚,Mirrors的实施在以下的快速来源中:

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

答案 1 :(得分:1)

po object.customDescription as NSString
相关问题