microsoft / WinObjC

Objective-C for Windows
MIT License
6.24k stars 809 forks source link

NSJSONSerialization: Memory leak in dataWithJSONObject : #2858

Open jboich opened 6 years ago

jboich commented 6 years ago

Visual Studio 2017 profiler shows memory leak in dataWithJSONObject method of NSJSONSerialization. (please see screenshots attached)

The snapshot was taken before and after clicking the button.

@interface ViewController() {
    UIButton *button;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    button = [UIButton buttonWithType : UIButtonTypeCustom];
    [button addTarget : self
        action : @selector(buttonAction : )
        forControlEvents : UIControlEventTouchUpInside];
    [button setTitle : @"NSJSONSerialization Test" forState : UIControlStateNormal];
    [button setTitleColor : [UIColor colorWithRed : 36 / 255.0 green : 71 / 255.0 blue : 113 / 255.0 alpha : 1.0] forState : UIControlStateNormal];
    button.frame = CGRectMake(80.0, 210.0, 260.0, 40.0);
    [self.view addSubview : button];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)buttonAction:(id)sender {
    [self testJsonSerializer];
}

-(void)testJsonSerializer {
    NSDictionary* test = @{ @"foo" : @{ @"bar" : @"1" }, @"foo2" : @{ @"bar2" : @"2" } };
    NSError *error;
    NSData *data = [NSJSONSerialization dataWithJSONObject : test options : 0 error : &error];

    data = nil;
    test = nil;

}
@end

screenshot 151

screenshot 152

DHowett-MSFT commented 6 years ago

Thanks for the detailed reproduction case! It looks like we're leaking a lot of Objective-C objects.

jboich commented 6 years ago

YAJL Framework is a great alternative to NSJSONSerializer