Hiren gardhariya
Hiren gardhariya

Reputation: 1257

Sorting NSDictionary which contains another dictionary

I face the problem, when i sort the dictionary, i can't get output from this. here i show my NSMutableDictionary which contains.

ReasonMst is my NSMutableDictionary.

Printing description of ReasonMst:
{
1 =     {
    nReasonNo = 1;
    vReasonCode = 1;
    vReasonDesc = "Office Purpose";
    vReasonType = O;
};
10 =     {
    nReasonNo = 10;
    vReasonCode = 10;
    vReasonDesc = Transit;
    vReasonType = O;
};
2 =     {
    nReasonNo = 2;
    vReasonCode = 2;
    vReasonDesc = Personal;
    vReasonType = O;
};
3 =     {
    nReasonNo = 3;
    vReasonCode = 3;
    vReasonDesc = Specific;
    vReasonType = O;
};
4 =     {
    nReasonNo = 4;
    vReasonCode = 4;
    vReasonDesc = "Meeting";
    vReasonType = I;
};
5 =     {
    nReasonNo = 5;
    vReasonCode = 5;
    vReasonDesc = "Meeting arrange";
    vReasonType = I;
};
6 =     {
    nReasonNo = 6;
    vReasonCode = 6;
    vReasonDesc = "NATIONAL CONFERENCE";
    vReasonType = I;
};
7 =     {
    nReasonNo = 7;
    vReasonCode = 7;
    vReasonDesc = Other;
    vReasonType = O;
};
8 =     {
    nReasonNo = 8;
    vReasonCode = 8;
    vReasonDesc = "Briefing Meeting";
    vReasonType = I;
};
9 =     {
    nReasonNo = 9;
    vReasonCode = 9;
    vReasonDesc = "Meeting At HO";
    vReasonType = I;
};
KeyList =     (
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    ""
);
}

i want to sort this NSMutableDictionary to vReasonDesc wise. Can any one tell me how can i do this easiest way ?

Upvotes: 1

Views: 226

Answers (1)

Neo
Neo

Reputation: 2807

Suppose ReasonMst is your NSMutableDictionary, do this

NSArray *key=[[NSArray alloc]initWithArray:[ReasonMst objectForKey:@"KeyList"]];
NSMutableArray *vReasonDesc=[[NSMutableArray alloc]init];
NSMutableArray *sortedKeys=[[NSMutableArray alloc]initWithArray:nil];
NSDictionary *tempDict=[[NSDictionary alloc]init];

for (int i=0; i<[key count]; i++) {
    [vReasonDesc addObject:[[ReasonMst objectForKey:[key objectAtIndex:i]]objectForKey:@"vReasonDesc"]];
}
[vReasonDesc sortUsingSelector:@selector(caseInsensitiveCompare:)];    

for (int i=0; i<[vReasonDesc count]; i++) {
    for (int j=0; j<[key count]; j++) {
        tempDict=[ReasonMst objectForKey:[key objectAtIndex:j]];
        NSLog(@"%@ ... %@",[vReasonDesc objectAtIndex:i], tempDict);
        if ([[tempDict objectForKey:@"vReasonDesc"]isEqualToString:[vReasonDesc objectAtIndex:i]]) {
            [sortedKeys addObject:[tempDict objectForKey:@"vReasonNo"]];
        }
    }
}

NSLog(@"sdafa %@",sortedKeys);

sortedKeys contain the keys sorted according to your vReasonDesc values... now you can access your ReasonMst according to the keys in sortedKeys which inorder.

for (int i=0; i<[sortedKeys count]; i++) {
    NSLog (@"%@",[ReasonMst objectForKey:[sortedKeys objectAtIndex:i]]);
}

Upvotes: 1

Related Questions