- [NSString dataUsingEncoding:] gives garbage at the end of the line in iOS 9, not iOS 8

The following code works fine on iOS 8, but when launched on iOS 9.0.2 I get some odd results:

NSString * input = @"Hi there";
NSData * data = [input dataUsingEncoding:NSASCIIStringEncoding];
Byte *byteData = (Byte*)malloc(data.length);
memcpy(byteData, [data bytes], data.length);

NSString * result = [NSString stringWithCString:(const char*)byteData encoding:NSASCIIStringEncoding];
NSLog(@"Result: %@", result);

iOS 8.4 (iPhone 6 Plus) byteData-Hi there

iOS 9.0.2 (iPhone 6S) byteData-Hi there\xb6<M\x13

In iOS 9, I end up loading garbage at the end of the line.

This seems like a problem with 32-bit and 64-bit versions, since on iOS 9 the data byte length is twice as long?

Apple has a table from 32 to 64 bits: https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaTouch64BitGuide/Major64-BitChanges/Major64-BitChanges.html

data.length unsigned long long. malloc? 8 data.length iOS.

, , . , - .

!

,

NSString * result = [[NSString alloc] initWithBytes:byteData length:data.length encoding:NSASCIIStringEncoding];

, iOS

NSString * result = [NSString stringWithCString:(const char*)byteData encoding:NSASCIIStringEncoding];
+4
1

"C" NUL. data dataUsingEncoding:, data C.

stringWithCString:encoding: ( NUL-), undefined , , .

cStringUsingEncoding: data, NULL.

+6

Source: https://habr.com/ru/post/1612813/


All Articles