tags:

views:

58

answers:

2

I am trying to call objectForKey: on an nsdictionary ivar, but I get an EXC_BAD_ACCESS error. The nsdictionary is created using the JSON-framework and then retained. The first time I use it (just after I create it, same run loop) it works perfectly fine, but when I try to access it later nothing works. I am doing this code to try to figure out what is wrong:

if (resultsDic == nil) {
    NSLog(@"results dic is nil.");
}
if ( [resultsDic respondsToSelector:@selector(objectForKey:)] ) {
    NSLog(@"resultsDic should respond to objectForKey:");
}

The dictionary is never nil, but it always crashes on respondsToSelector. any ideas?

addition: These are the other places, besides above, that the dictionary gets interacted with:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [connection release];

    //get the data in a usable form
    NSString *jsonString = [[NSString alloc] initWithData:downloadedData encoding:NSUTF8StringEncoding];
    resultsDic = [jsonString JSONValue];

    [self processResults];

    NSLog(@"Success. Received %d bytes of data",[downloadedData length]);
    [downloadedData release];
    [jsonString release];
}



- (void)processResults
{
        NSArray *resultsArr = [resultsDic objectForKey:@"results"];
                CLLocationCoordinate2D coordinate = [self coordinateFromResult:[resultsArr objectAtIndex:0]];
        NSLog(@"lat: %f lng: %f", coordinate.latitude, coordinate.longitude);
}

- (void)dealloc {
  [resultsDic release];
  [super dealloc];
}
A: 

After somethings retain count is decreased to 0, the object gets deallocated. This is not the same as setting it to nil. It will not be nil. Whilst you can send messages to nil, sending a message to a released object will result in an EXC_BAD_ACCESS error. If you post some of the code where it is created and used, maybe we can help you debug it. Try retaining it twice at the beginning. it's nit an elegant solution, but it might work as a quick fix.

Tom H
ah, thank you for the explanation. adding a retain right after it is created makes it work, now i need to check for leaks. the zombie tool is grayed out for me but im going to get that running too
aks
According to the leak instrument, the dictionary isn't leaking. Does this mean that I should have retained it anyway and the retain I added is necessary?
aks
Most likely. If everyone is following the proper rules, the dictionary you got back will have been autoreleased (which is why you were able to work with it right away, but it got deallocated later). So if you want to keep it, retain it.
bobDevil
A: 

Sounds like a classic zombie. Run it again with the environment variable NSZombieEnabled set to YES (or use the Zombies instrument in Instruments.app). That should give you much more information about what's going on.

Dave DeLong
thanks, didnt know about that tool (pretty big noob here)
aks