Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a var_dump in Xcode?

Tags:

xcode

ios

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

Is there a function for this?

like image 507
Arian Faurtosh Avatar asked Nov 11 '13 20:11

Arian Faurtosh


People also ask

What is Var_dump () used for?

The var_dump() function is used to dump information about a variable. This function displays structured information such as type and value of the given variable. Arrays and objects are explored recursively with values indented to show structure. This function is also effective with expressions.

Is there a Var_dump in JavaScript?

The var_dump equivalent in JavaScript? Simply, there isn't one. Prints an interactive listing of all properties of the object. This looks identical to the view that you would see in the DOM tab.


3 Answers

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

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
like image 144
little Avatar answered Sep 21 '22 12:09

little


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 *)description for those classes.

like image 37
TotoroTotoro Avatar answered Sep 22 '22 12:09

TotoroTotoro


NSObject defines the description method, 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.

This is for instance the case of NSArray and NSDictionary, whose implementation produces a NSString representing the objects stored in the collection.

When you do

NSLog(@"%@", anObject);

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

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.

like image 29
Gabriele Petronella Avatar answered Sep 19 '22 12:09

Gabriele Petronella