NSMutableDictionary 没有得到预期的输出。
Posted
技术标签:
【中文标题】NSMutableDictionary 没有得到预期的输出。【英文标题】:NSMutableDictionary not getting expected output. 【发布时间】:2011-12-07 17:08:14 【问题描述】:它只为 NSMutableDictionary 输出一组,而不是两者。我想使用 NSMutableDictionary (JSONRepresentation) 创建一个 JSON 请求。
// My code
NSArray *keysEndpoint = [NSArray arrayWithObjects:@"ID", @"Name", @"EndpointType", nil];
NSArray *objectEndpoint = [NSArray arrayWithObjects:@"622", @"Brand", @"0", nil];
NSArray *keysEndpoint1 = [NSArray arrayWithObjects:@"ID", @"Name", @"EndpointType", nil];
NSArray *objectEndpoint1 = [NSArray arrayWithObjects:@"595", @"CK-05052011", @"1", nil];
NSMutableArray *keys1 = [[NSMutableArray alloc] initWithCapacity:0];
NSMutableArray *objects1 = [[NSMutableArray alloc] initWithCapacity:0];
[keys1 addObjectsFromArray:keysEndpoint];
[keys1 addObjectsFromArray:keysEndpoint1];
NSLog(@"Key Dic: %@", keys1);
[objects1 addObjectsFromArray:objectEndpoint];
[objects1 addObjectsFromArray:objectEndpoint1];
NSLog(@"Obje Dic: %@", objects1);
NSMutableDictionary *testMut = [NSMutableDictionary dictionaryWithObjects:objects1 forKeys:keys1];
NSLog(@"Test Dic: %@", testMut);
输出是这样的:
Test Dic:
EndpointType = 1;
ID = 595;
Name = "CK-05052011";
我想要的扩展输出是:
Test Dic:
EndpointType = 1;
ID = 595;
Name = "CK-05052011";
EndpointType = 0;
ID = 622;
Name = "Brand";
【问题讨论】:
【参考方案1】:对于字典,两次添加相同的键将覆盖第一组键。你应该有一个 NSMutableDictionary 的 NSMutableArray
NSArray *keysEndpoint = [NSArray arrayWithObjects:@"ID", @"Name", @"EndpointType", nil];
NSArray *objectEndpoint = [NSArray arrayWithObjects:@"622", @"Brand", @"0", nil];
NSArray *keysEndpoint1 = [NSArray arrayWithObjects:@"ID", @"Name", @"EndpointType", nil];
NSArray *objectEndpoint1 = [NSArray arrayWithObjects:@"595", @"CK-05052011", @"1", nil];
NSMutableDictionary *testMut = [NSMutableDictionary dictionaryWithObjects:objectsEndpoint forKeys:keysEndpoint];
NSMutableDictionary *testMut1 = [NSMutableDictionary dictionaryWithObjects:objectsEndpoint1 forKeys:keysEndpoint1];
NSMutableArray * dictArray = [NSMutableArray arrayWithObjects:testMut,testMut1,nil];
NSLog(@"Test DictArray: %@", dictArray);
【讨论】:
谢谢,这可以工作,但问题是,我有超过 20 个数组用于关键点和对象端点。我无法创建 20 个 NSMutableDictionary。有没有办法以编程方式做到这一点? @AmitVyawahare 您从哪里获取关键点和对象端点数据?绝对可以动态填充这些数据。要将数据转换为 json 对象,您可以在 SO 上查找 SBJson 或 JSONKit 的示例。以上是关于NSMutableDictionary 没有得到预期的输出。的主要内容,如果未能解决你的问题,请参考以下文章
NSInvalidArgumentException/copyWithZone 异常与 NSMutableDictionary
“NSMutableDictionary”类型的值在 swift 中没有成员“字符串”
如何在 NSMutableDictionary 中保留部分分数