NSDictionary基本功能问题

时间:2013-05-15 22:07:46

标签: objective-c

我有一些JSON数据,我试图将其放入NSDictionary中。

使用以下代码将数据放入字典:

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

我的问题是,当我尝试运行我希望检索数据时,我会遇到异常。代码是:

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

所以我使用代码制作了自己的字典:

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

这很好。所以我查看了调试器,发现两个词典之间存在差异。

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

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

我不确定为什么会这样做。是否有人能够了解情况,并建议我如何在NSDictionary tempDict中访问KVP?

1 个答案:

答案 0 :(得分:2)

看起来JSON文件中的根对象是一个包含单个元素(字典)的数组。试试这个:

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

注意:向一个没有立即alloc的对象发送init很少(如果有的话)你想做什么。使用alloc / init将返回引用计数为1的对象,或使用返回自动释放对象的类方法,如JSONObjectWithData:...