Forgive me for a potentially silly question here, but in other programming languages (scripting ones like PHP or Perl) it is often easy to dump everything contained within a variable.
For instance, in PHP there are the var_dump()
or print_r()
functions. Perl has the Data::Dumper
CPAN class, etc etc.
Is there something like this for Objective-C? It would be very convenient in a few cases to be able to dump everything like that, instead of using gdb to inspect each variable.
In Cocoa, there is no "dump" like PHP's print_r or python's repr since there is no textual format that "represents" an object as in those languages. If you use
or
or
you will get (logged to console in the first case), the result of
[myObj description]
, a method defined inNSObject
for the purpose of printing a description (not a dump) of an object.If you invoke
po myObj
in gdb, you get[myObj debugDescription]
(often the same asdescription
, but not always).Classes like
NSArray
andNSDictionary
andNSData
overridedescription
to print a pretty useful recursive description of their contents, but the default[NSObject description]
prints only the pointer value corresponding to the instance.If you control the code for the types in question, you can override their
description
ordebugDescription
methods to return anything you want. If not, you could override thedescription
ordebugDescription
method using a category, or use a category to define amyDebugDescription
or some such that you could then invoke from gdb usingpo [myObj myDebugDescription]
.Use NSLog() to dump contents of objects. For example:
NSLog has a printf-style format string (expects an NSString object) followed by a variable list of parameters, just like printf. The replacement character %@ represents an object the description method on an object. This is useful for dumping most Objective-C objects in Cocoa.
If you want to dump the contents of an object using gdb (I see you tagged this with gdb), use the special "po" directive instead of print. For example:
will cause gdb to dump the myData object. po is a shortcut for print-object.
you can also use the gdb print object command to quickly view an object in the debugger:
This will be basically the same as calling NSLog(...) from within your code.
Also useful when printing out NSData that contains ASCII data is:
Be careful with NSLog logging -> you most likely don't want it in production code.
You may want to use an alternate logging function that calls NSLog when your product is running in debug mode.
I usualy go with this to "debug" NSArray contents:
The code will enumerate all objects in the NSArray
myarray
, and then iterate through and print every object.Hope this can be useful for someone!