5

I've been using stringWithUTF8String to convert my NSData to NSString as follows:

if ([[NSString stringWithUTF8String:[responsedata bytes]] isEqualToString:@"SUCCESS"]){
    dostuff...
}

It's been working fine; however, since the 8.2 iOS update, [[NSString stringWithUTF8String:[responsedata bytes]] returned nil.

I solved the problem by using the following code:

NSString *responseDataString = [[NSString alloc] initWithData:responsedata encoding:NSUTF8StringEncoding];

if ([responseDataString isEqualToString:@"SUCCESS"]){
    dostuff...
}

In both cases responsedata's printed description was the same: <OS_dispatch_data: data[0x7aeb6500] = { leaf, size = 7, buf = 0x7c390360 }>

My question is: WHY would the first option return nil, and WHY suddenly after the iOS 8.2 update?

Stephan
  • 881
  • 9
  • 24

1 Answers1

4

stringWithUTF8String is expecting a NUL terminated buffer, but your NSData is not NUL terminated.

In your example your NSData contains 7 bytes, and the value you are expecting is also 7 characters. This may work occasionally when there happens to be a NUL following the memory in your NSData, but it often will not work.

The only safe way to convert a non-NUL terminated NSData is to also tell NSString the length of your buffer, like you are doing in your solution.

kevin
  • 2,021
  • 21
  • 20
  • Thanks for explaining! So it's not necessarily an iOS 8.2 issue, but I was rather just 'lucky' that it worked previously... – Stephan Mar 17 '15 at 05:46