varun varun - 6 months ago 15
Objective-C Question

How to create customised nsdictionary from two nsarrays

I have two arrays like this

idArray:(
"548c2afe-5943-4929-9c6b-b544f5022115-sff45v-kjsa68f",
"656e8481-f2d5-4843-bebd-883f1b0f79d0-ksfns-gg456gg"
)

namesArray:(
"king",
"queen"
)


I want to make a dictionary which looks like this

[{
"id" : "548c2afe-5943-4929-9c6b-b544f5022115-sff45v-kjsa68f",
"name" : "king"
},
{
"id" : "3656e8481-f2d5-4843-bebd-883f1b0f79d0-ksfns-gg456gg",
"name" : "queen"
}]


Help me in this issue. i have tried this

NSDictionary *fullDictionary = @{@"id": userarray, @"scandat": scandatesarray};

NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:fullDictionary options:0 error:&error];
NSLog(@"%@", fullDictionary);


and the output is

{
id = (
"656e8481-f2d5-4843-bebd-883f1b0f79d0",
"548c2afe-5943-4929-9c6b-b544f5022115"
);
scandat = (
"2016-05-28 16:50:30",
"2016-05-28 16:50:59"
);
}

Answer

You are not making a dictionary - your target object is an NSArray containing NSDictionary objects as its elements.

NSMutableArray *res = [NSMutableArray array];
NSArray *keys = @[@"id", @"name"];
for (int i = 0 ; i != idArray.count ; i++) {
    NSDictionary *dict = [NSDictionary
        dictionaryWithObjects: @[idArray[i], nameArray[i]]
        forKeys: keys
    ];
    [res addObject:dict];
}
Comments