Xcode 中有 var_dump 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19914895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 04:17:02  来源:igfitidea点击:

Is there a var_dump in Xcode?

iosxcode

提问by Arian Faurtosh

I come from a php background... so I was wondering if there was such a thing as var_dumpfor Xcode, I know about NSLogbut I want it to act like var_dump.

我来自 php 背景......所以我想知道是否有像var_dumpXcode这样的东西,我知道NSLog但我希望它像var_dump.

Is there a function for this?

有这个功能吗?

采纳答案by Macondo2Seattle

In code:

在代码中:

NSLog(@"%@", myVar);

which is equivalent to

这相当于

NSLog(@"%@", [myVar description]);

Or in the debugger: right click on the variable, and select "Print description".

或者在调试器中:右键单击变量,然后选择“打印描述”。

If you want to inspect objects of your own classes this way, you need to implement the method -(NSString *)descriptionfor those classes.

如果您想以这种方式检查您自己的类的对象,您需要-(NSString *)description为这些类实现该方法。

回答by little

In swift you can use dump(var) which uses mirror for introspection and useful for classes.

在 swift 中,您可以使用 dump(var) ,它使用镜像进行自省并对类有用。

For example:

例如:

let pet = Pet(name:"Max", age: 4)
let adam = Person(name:"Adam", age: 30, pet:pet)

print("\(pet)")
print("\(adam)")
print("======")
dump(pet)
dump(adam)

The output will be:

输出将是:

Pet
Person
======
? Pet #0
  - name: "Max"
  - age: 4
? Person #0
  - name: "Adam"
  - age: 30
  ? pet: Optional(Pet)
    ? some: Pet #1
      - name: "Max"
      - age: 4

回答by Gabriele Petronella

NSObjectdefines the descriptionmethod, which provides a description of the object. The default implementation just prints the name of the class, but it's commonly overridden by subclasses to provide a more meaningful description of their content.

NSObject定义description方法,该方法提供对象的描述。默认实现只打印类的名称,但它通常被子类覆盖以提供对其内容更有意义的描述。

This is for instance the case of NSArrayand NSDictionary, whose implementation produces a NSStringrepresenting the objects stored in the collection.

这是例如NSArrayand的情况NSDictionary,它的实现产生一个NSString代表存储在集合中的对象。

When you do

当你做

NSLog(@"%@", anObject);

descriptionis automatically called on the object to retrieve a textual representation of it.

description自动调用对象以检索它的文本表示。

Also in the debugger you can do

同样在调试器中你可以做

po anObject

to achieve the same result.

达到相同的结果。

Bottom line, if you need to provide a representation of a custom class you implemented, the way to go is to override description.

最重要的是,如果您需要提供您实现的自定义类的表示,那么要走的路是覆盖description.