NSMutableDictionary未获得预期的输出。

时间:2011-12-07 17:08:15

标签: objective-c ios json nsdictionary nsmutabledictionary

它只为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";
}

我想要的Expexted输出是:

Test Dic: {
    EndpointType = 1;
    ID = 595;
    Name = "CK-05052011";
} 
{
    EndpointType = 0;
    ID = 622;
    Name = "Brand";
}

1 个答案:

答案 0 :(得分:1)

对于字典,两次添加相同的键将覆盖第一组键。你应该有一个NSMutableArray of NSMutableDictionary

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);