이 예상대로 바로 작동합니다
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]);
따라서 영업 이익의 코드가 실제로했던 것을 증명,
__NSArrayM
이
NSMutableArray
의 개인 서브 클래스임을 밝혀지지 않았다 단지의 경우 ...
2012-03-28 18:09:53.770 ExampleRunner[42830:707] NSMutableArray
: 363,210
... 우리는 콘솔에 다음과 같은 출력을 얻을 예상대로 작동합니다 (그의 NSLog
성명을 제외하고).
편집
아, 그리고 그 길을, 다음 코드 줄에 의해 ...
NSLog(@"%d", [[dict objectForKey:@"objs"] isKindOfClass:[NSMutableArray class]]);
... 다음 콘솔 출력 결과 :
2012-03-28 18:19:19.721 ExampleRunner[42886:707] 1
EDIT (변경된 질문에 응답)
흥미 롭습니다 ... 버그처럼 보입니다. 다음 코드를 감안할 때 :
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
디버그 콘솔에서'po [[listOfObjects class] superclass]'를 실행할 때의 결과는 무엇입니까? – warrenm
Mac OS X 10.7에서이 문제를 확인할 수 있습니다 - 빈 배열 만 영향을받는 것 같습니다. 10.8에서 수정 된 것 같습니다. – blutfink