Skip to content

Instantly share code, notes, and snippets.

@0xced
Created January 22, 2016 16:23
Show Gist options
  • Save 0xced/56035d2f57254cf518b5 to your computer and use it in GitHub Desktop.
Save 0xced/56035d2f57254cf518b5 to your computer and use it in GitHub Desktop.
Convoluted way to get [NSJSONSerialization dataWithJSONObject:options:error:] to return an error
// http://twitter.com/nicklockwood/status/690540488433274881
// @0xced hmm, you're right. So under what circumstances *does* it populate the error param? Why even have it at all?
// http://twitter.com/0xced/status/690543445404991488
// @nicklockwood Just disassembled again, seems it can errors if a string fails to convert to UTF8. @nst021 Idea how to produce such a string?
// http://twitter.com/mikeash/status/690564095322542081
// mikeash: @0xced @nicklockwood @nst021 Maybe try an NSString containing half of a surrogate pair.
#import <Foundation/Foundation.h>
int main(int argc, char *argv[])
{
@autoreleasepool
{
NSString *string = [[NSString alloc] initWithBytes:"\xd8\x00" length:2 encoding:NSUTF16StringEncoding];
NSLog(@"string pointer = %p", string);
NSLog(@"string = %@", string);
NSLog(@"string.UTF8String = %s", string.UTF8String);
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:@{@"string": string} options:0 error:&error];
NSLog(@"%@", data ?: error);
}
}
@skyline75489
Copy link

Does't work on 10.11.6. The string is simply nil.

@hovox
Copy link

hovox commented Oct 11, 2019

seems this is crashing in iOS 13 with bad access, is it regression ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment