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?
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?
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
.