ammy1 ammy1 - 4 months ago 8
iOS Question

storing multiples values for particular key in an array of dictionaries not working iOS

i want to have an array which stores dictionaries with some key-value pair like shown below.

add = (
{
ans = abc;
que = Fdgdf;
},
{
ans = hi;
que = hello;
},
{
ans = GM;
que = dosa;
}
)


Here is what i tried.

for (int i=0; i<=[addKeyArray count]; i++) {

[_addDictNewQA setObject:[addKeyarray objectAtIndex:i] forKey:@"que"];
[_addDictNewQA setObject:[addValuesArray objectAtIndex:i] forKey:@"ans"];
[_addArrayNewQA addObject:_addDictNewQA];
}


here addKeyArray is the array which holds all the 'que' elements and addValuesArrray holds all the 'and' elements. but when i set these arrays to dictionary objects and add that dictionary to new array(_addArrayNewQA), it only display the last element like this-

add = (
{
ans = GM;
que = dosa;
},
{
ans = GM;
que = dosa;
},
{
ans = GM;
que = dosa;
}
)


Can anyone please tell me whats wrong in my code. Any help is appreciated.

Answer

That is because you are setting values in same object of NSMutableDictionary, also you dont need to have the NSMutableDictionary as global as you are using it in the for loop only.

You need to create new dictionary

 for (int i=0; i<=[addKeyArray count]; i++) {
    NSMutableDictionary *_addDictNewQA = [NSMutableDictionary new];
    [_addDictNewQA setObject:[addKeyarray objectAtIndex:i] forKey:@"que"];
    [_addDictNewQA setObject:[addValuesArray objectAtIndex:i] forKey:@"ans"];
}
[_addArrayNewQA addObject:_addDictNewQA];
Comments