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?
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.
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.
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
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With