Search code examples
jsonios5grand-central-dispatchtouchjson

Parsing JSON using Grand Central Dispatch in connectionDidFinishLoading:?


I'm am performing JSON deserialization with JSONTouch, but it's taking too long and it's blocking the UI, so I've tried to make a GCD background queue to put the serialization in a background thread. Sometimes it runs fine, but sometimes I get a EXC_BAD_ACCESS on deserializeAsDictionary:weakSelf.mutableData error:&theError];.

I'm at a loss as to why. I've made mutableData an atomic property. I'm making 3 requests at once, so I guess something it has to do with threads trying to access the mutableData? or perhaps mutableData is not in a good state when the block runs?

Thanks a lot!

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
     __weak myViewController *weakSelf = self;

    dispatch_queue_t updateQueue = dispatch_queue_create("parse json", NULL);
    dispatch_async(updateQueue, ^{
        NSError *theError = nil;

    // This is the call that gives me EXC_BAD_ACCESS
    NSDictionary *dict = [[CJSONDeserializer deserializer] 
       deserializeAsDictionary:weakSelf.mutableData error:&theError];

   dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf setMutableData: nil];
      });
   });
   dispatch_release(updateQueue);
}

Solution

  • The problem was that I was using one mutableData object to store the response of the three requests, and when one connection finished and the connectionDidFinishLoading: handler was reading the data, another connection in another thread was appending data to it.

    I created a separate NSMutableData object for every request, and added code to connectionDidFinishLoading: so that it reads from the correct NSMutableData object.

    My application is very responsive now that the handler is running in another GCD queue!