Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringWithUTF8String returning nil since iOS 8.2 update

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?

like image 664
Stephan Avatar asked Sep 28 '22 13:09

Stephan


1 Answers

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.

like image 92
kevin Avatar answered Oct 06 '22 19:10

kevin