I'm facing a problem that I don't understand. Before beginning to explain it, even if I have worked on a Swift project this year that was using some Objective-C, I am new to this language and its concepts.
So, there is my problem : I want to access the bytes of an NSData object. I know there several ways to do so :
[data bytes];
data.bytes;
[data getBytes: dest, length: [data length]];
But each method doesn't return the same value as the console, when I'm using po [data bytes]
.
Can you explain me why this happens ? I don't really understand what I'm missing.
Thanks.
data
and data.bytes
are of two totally different types. data
is an instance of NSData
, while data.bytes
is a raw pointer (const void *
). When you call po
in the debugger (short for "print object"), it will call -description
on things which inherit from NSObject
, or just print the value if they do not.
In this case, since data
is an NSData
(which has -description
), if you po data
, it calls [data description]
and prints the result of that out; since NSData
knows how to nicely format its contents, it will print nicely.
However, since data.bytes
is a void *
, there is no way for the debugger to know how to print it (void *
can point to anything; how to interpret it is totally up to you) so it just prints out the pointer itself.
If you want to print the data from the debugger directly, you can tell it how to interpret the pointer and print it out. If you know that the data blob is n
bytes long, you can run the following command:
p/x *(uint8_t (*)[<n>])data.bytes
where <n>
is replaced with the literal length of the data (e.g. uint8_t (*)[8])
). *(uint8_t (*)[<n>])data.bytes
tells the debugger to reinterpret data.bytes
as an array of n
bytes (giving it the length so it knows how much data to read from memory) while p/x
tells it to print the hex values of the bytes it finds.