I have an Input Array of Dictionaries :
myArray = (
{
name:"abc";
time:"6:00";
},
{
name:"xyz";
time:"7:00";
},
.
.
)
I want Output Dictionary like this :
myDictionary = {
"6:00":(
{
name:"abc";
time:"6:00";
},
.
.
)
"7:00":(
{
name:"xyz";
time:"7:00";
},
.
.
)
}
What I tried :
I succeeded to get an array of distinct times
using this line :
NSArray *arrTempKeys = [myArray valueForKeyPath:@"@distinctUnionOfObjects.Time"];
and then used the predicate inside for loop
for arrTempKeys
, to get all the dictionaries with same time
value :
NSPredicate *pred = [NSPredicate predicateWithFormat:@"Date == %@",str];
NSArray *arrTemp = [myArray filteredArrayUsingPredicate:pred];
Finally, I assigned this arrTemp
as an Object for the Key time
and got the desired result.
What I want :
I know there are many other ways to get this output. But I just want to know if there is any single KVC
coding line or any other optimum way available to do this thing.
You want too much. Just write a simple loop. It will be the most efficient, clearest, and probably the most reliable solution:
NSMutableDictionary* myDict = [NSMutableDictionary dictionary];
for (NSDictionary* innerDict in myArray) {
NSString* time = innerDict[@"time"];
NSMutableArray* innerArray = myDict[time];
if (innerArray == nil) {
innerArray = [NSMutableArray array];
[myDict setValue:innerArray forKey:time];
}
[innerArray addObject:innerDict];
}