這個工程就像預期:
NSString *s = @"{ \"objs\": [ \"a\", \"b\" ] }";
NSData *d = [NSData dataWithBytes:[s UTF8String] length:[s length]];
id dict = [NSJSONSerialization JSONObjectWithData:d options:NSJSONReadingMutableContainers error:NULL];
NSLog(@"%@", dict);
[[dict objectForKey:@"objs"] addObject:@"c"];
NSLog(@"%@", dict);
NSLog(@"%@", [[dict objectForKey:@"objs"] class]);
這裏是控制檯輸出:
2012-03-28 13:49:46.224 ExampleRunner[42526:707] {
objs = (
a,
b
);
}
2012-03-28 13:49:46.225 ExampleRunner[42526:707] {
objs = (
a,
b,
c
);
}
2012-03-28 13:49:46.225 ExampleRunner[42526:707] __NSArrayM
編輯
注意,如果我們下面的行追加到上面的代碼.. 。
NSLog(@"%@", [[dict objectForKey:@"objs"] superclass]);
...我們得到的控制檯上的輸出如下:
2012-03-28 18:09:53.770 ExampleRunner[42830:707] NSMutableArray
...以防萬一,目前還不清楚的是__NSArrayM
是NSMutableArray
私有子類,由此證明了OP的代碼確實按預期工作(他的NSLog
聲明除外)。
編輯
哦,順便說一下,下面的代碼行...
NSLog(@"%d", [[dict objectForKey:@"objs"] isKindOfClass:[NSMutableArray class]]);
...結果在下面的控制檯輸出:
2012-03-28 18:19:19.721 ExampleRunner[42886:707] 1
編輯(迴應改變的問題)
有趣...看起來像一個錯誤。考慮下面的代碼:
NSData *dictData2 = [@"{ \"foo\": \"bar\" }" dataUsingEncoding:NSUTF8StringEncoding];
id dict2 = [NSJSONSerialization JSONObjectWithData:dictData2 options:NSJSONReadingMutableContainers error:NULL];
NSLog(@"%@", [dict2 class]);
NSLog(@"%@", [dict2 superclass]);
NSLog(@"%d", [dict2 isKindOfClass:[NSMutableDictionary class]]);
// This works...
[dict2 setObject:@"quux" forKey:@"baz"];
NSLog(@"%@", dict2);
NSData *dictData = [@"{}" dataUsingEncoding:NSUTF8StringEncoding];
id emptyDict = [NSJSONSerialization JSONObjectWithData:dictData options:NSJSONReadingMutableContainers error:NULL];
NSLog(@"%@", [emptyDict class]);
NSLog(@"%@", [emptyDict superclass]);
NSLog(@"%d", [emptyDict isKindOfClass:[NSMutableDictionary class]]);
//...but this fails:
[emptyDict setObject:@"quux" forKey:@"baz"];
NSLog(@"%@", emptyDict);
這裏是控制檯輸出:
2012-03-29 09:40:52.781 ExampleRunner[43816:707] NSMutableDictionary
2012-03-29 09:40:52.782 ExampleRunner[43816:707] 1
2012-03-29 09:40:52.782 ExampleRunner[43816:707] __NSCFDictionary
2012-03-29 09:40:52.782 ExampleRunner[43816:707] NSMutableDictionary
2012-03-29 09:40:52.783 ExampleRunner[43816:707] 1
2012-03-29 09:40:52.783 ExampleRunner[43816:707] {
baz = quux;
foo = bar;
}
2012-03-29 09:40:52.784 ExampleRunner[43816:707] __NSCFDictionary
2012-03-29 09:40:52.784 ExampleRunner[43816:707] NSMutableDictionary
2012-03-29 09:40:52.784 ExampleRunner[43816:707] 1
2012-03-29 09:40:52.785 ExampleRunner[43816:707] NSException: -[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object
所以空數組,並以這種方式創建的字典似乎並沒有像預期的那樣。
你確定他們沒有出現作爲NSMutableDictionary? – Zalykr 2012-03-28 17:44:55
在調試控制檯中運行'po [[listOfObjects class] superclass]'時,輸出是什麼? – warrenm 2012-03-28 17:45:48
我可以在Mac OS X 10.7上確認此問題 - 只有空數組似乎受到影響。它似乎在10.8中被固定。 – blutfink 2013-01-10 22:01:36