Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Viewing NSData contents in Xcode

I am running Xcode and I would like to dump out a NSData*. The variable in question is buffer. Is there a way to do this through the UI or the GDB debugger?

This is what I see at runtime

Edit

I've moved my notes into an answer.

like image 533
Brian Avatar asked Jul 17 '12 21:07

Brian


4 Answers

No one has ever correctly answered the question. After 2 years I think it's time for one :)

Assuming you have in your code

NSData* myData;

Then in lldb you type

me read `[myData bytes]` -c`[myData length]`

If the format of the dump is not to your liking you can add '-t ' for example

me read `[myData bytes]` -c`[myData length]` -t int

For more help type

help me read

in lldb

like image 87
GarMan Avatar answered Oct 21 '22 20:10

GarMan


From Xcode 5 (lldb), you can use the following:

po (NSString *)[[NSString alloc] initWithData:buffer encoding:4]

Note that this assumes your NSData instance is encoded with NSUTF8StringEncoding, but you can look up the other values in the headers or the documentation.

So if you're debugging something like a JSON request that's wrapped up in an NSURLSessionDataTask, the request data is in task.originalRequest.httpBody, and you can view that in the debugger with

po (NSString *)[[NSString alloc] initWithData:task.originalRequest.HTTPBody encoding:4]
like image 45
Kevin Clifton Avatar answered Oct 21 '22 19:10

Kevin Clifton


In lldb, the following works to let you examine the contents of NSData objects:

You can get the address of the bytes for use with various debugger commands like this:

p (void *)[buffer bytes]

You see something like this:

(void *) $32 = 0x0b5e11f0

If you know the underlying data is a string, you can do this:

p (char *)[buffer bytes]

and the debugger will output:

(char *) $33 = 0x0b5e11f0 "This is the string in your NSData, for example."
like image 16
Troy Avatar answered Oct 21 '22 20:10

Troy


In Swift this should do the trick:

po String(data:buffer!, encoding: NSUTF8StringEncoding)
like image 8
Max MacLeod Avatar answered Oct 21 '22 20:10

Max MacLeod