Jamesla
Jamesla

Reputation: 1408

Issue with NSDictionary basic functionality

I have some JSON data that I am trying to put into an NSDictionary.

The data is being put into the dictionary using the following code:

NSDictionary *tempDict = [NSDictionary alloc];
tempDict = [NSJSONSerialization JSONObjectWithData:urlData
                                           options:NSJSONReadingMutableContainers
                                             error:&error];

My issue is that when I try and run what I would expect to retrieve the data I am getting an exception. The code is:

NSLog([tempDict valueForKey:@"key"]);

So I made my own dictionary using the code:

NSDictionary *test = [[NSDictionary alloc]initWithObjectsAndKeys:@"teststring",@"1",@"teststring2",@"2", nil];
    NSLog([test valueForKey:@"1"]);

And that worked fine. So I looked at the debugger and found a difference between the two dictionaries.

tempDict    NSDictionary *  0x0920c190
    [0] id  0x0920c150   <----
        [0] key/value pair  
            key id  0x0920c100
            value   id  0x0920bf00
        [1] key/value pair   
            key id  0x0920c120
            value   id  0x0920c140

And:

test    NSDictionary *  0x0920c260
    [0] key/value pair  
        key id  0x0003a430
        value   id  0x0003a420
    [1] key/value pair  
        key id  0x0003a450
        value   id  0x0003a440

I am unsure why it is doing this. Is anybody able to shed any light on the situation and also advice how I can access the KVP's in the NSDictionary tempDict?

Upvotes: 1

Views: 50

Answers (1)

DrummerB
DrummerB

Reputation: 40211

Looks like the root object in your JSON file is an array with a single element (the dictionary). Try this:

NSArray *array = [NSJSONSerialization JSONObjectWithData:urlData
                                                 options:NSJSONReadingMutableContainers
                                                   error:&error];
NSDictionary *tempDict = array[0];

Note: Sending an alloc to an object without an immediate init is rarely (if ever) what you want to do. Either use alloc/init which will return an object with reference count 1, or use a class method that returns an autoreleased object, like JSONObjectWithData:....

Upvotes: 2

Related Questions