Skip to content

Instantly share code, notes, and snippets.

@roustem
Created September 1, 2011 18:11
Show Gist options
  • Save roustem/1186829 to your computer and use it in GitHub Desktop.
Save roustem/1186829 to your computer and use it in GitHub Desktop.
Bug in NSJSONSerialization
//
// main.m
// JSONTrouble
//
// Created by Roustem Karimov on 11-08-31.
// Copyright (c) 2011 AgileBits. All rights reserved.
//
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
@autoreleasepool {
/*
* Everything works as expected with a non-empty container.
*/
NSMutableArray *array1 = [NSMutableArray arrayWithCapacity:2];
[array1 addObject:@"Hello, World!"];
NSData *json = [NSJSONSerialization dataWithJSONObject:array1 options:0 error:NULL];
NSMutableArray *array2 = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableContainers error:NULL];
NSLog(@"array1: %@, array2: %@", [array1 className], [array2 className]);
assert([array2 isKindOfClass:[NSMutableArray class]]); // no problem here
/*
* Break when using an empty container.
*/
[array1 removeAllObjects];
json = [NSJSONSerialization dataWithJSONObject:array1 options:0 error:NULL];
array2 = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableContainers error:NULL];
NSLog(@"array1: %@, array2: %@", [array1 className], [array2 className]);
assert([array2 isKindOfClass:[NSMutableArray class]]); // Yay, bug!
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment