1

I try to get an NSString from NSData but I get a nil value. This is my code:

NSString *dataString = [[NSString alloc] initWithData:self.message.data encoding:NSUTF8StringEncoding];

When I log self.message.data I get:

Printing description of self->_message->_data:
<OS_dispatch_data: data[0x17e48290] = { leaf, size = 331233, buf = 0x3aac000 }>

That means my data is not nil…

Can anyone help?

skywinder
  • 21,291
  • 15
  • 93
  • 123
Nimrod Shai
  • 1,149
  • 13
  • 26
  • Where is this data coming from and in which format is this data sent? – Pavan Apr 21 '14 at 20:26
  • What is outputted if you do `NSLog(@"Class of self->_message->_data: %@", NSStringFromClass([self->_message->_data class]));`? – Rich Apr 21 '14 at 20:26
  • 1
    The `initWithData:encoding:` method expected an `NSData` object. What is your `self.message.data` object? – rmaddy Apr 21 '14 at 20:26
  • Interestingly there's also another [question](http://stackoverflow.com/questions/19434245/how-to-convert-os-dispatch-data-5018112-bytes-into-nsdata-to-put-into-uiimag) around this `OS_dispatch_data`! (Not that I'm saying this is a duplicate!) – Rich Apr 21 '14 at 20:29
  • Just noticed my data isn't a regular NSData as I thought. It is OS_Dispatch_Data. What is it? – Nimrod Shai Apr 21 '14 at 20:30
  • @NimrodShai see [this question/answers](http://stackoverflow.com/questions/9152851/how-to-convert-dispatch-data-t-to-nsdata) for more information about `OS_dispatch_data` :) – Rich Apr 21 '14 at 20:31
  • try using `po [self.message.data description]` in the debugger to get a printed description of the data. That will give insight into whether the data might be in the proper format to create a string out of... – NSGod Apr 21 '14 at 20:37
  • what's the encoding of the text in the NSData? – Daij-Djan Jul 15 '14 at 06:45

2 Answers2

1

As answer to your question in comments: OS_dispatch_data is dispatch_data_t which has toll-free bridging with NSData on iOS 7 and Mavericks. You can simply cast it to NSData *.

So, in your case you can write:

NSData *dataCast = self.message.data;
NSString *dataString = [[NSString alloc] initWithData:dataCast encoding:NSUTF8StringEncoding];

And now you get the correct string!

In my case it appeared, when AFNetworking cast internal NSMutableData to NSData.

And this simple cast helps me.


UPD: As @Daij-Djan mentioned: If it's not works - try to check your text encoding.

For example if you're yousing NSURLSessionTask:

NSURLSessionTask *task; // Your NSURLSessionTask
NSString *encoding = [[task response] textEncodingName];

In your case (NSUTF8StringEncoding) it should be "utf-8".

skywinder
  • 21,291
  • 15
  • 93
  • 123
0

Try UTF-16 encoding instead. It may be an error converting to UTF-8 if any data in there is not recognized.

C_Rod
  • 193
  • 10