Reputation: 512
I am trying to add datas to a dictionary using key value array but the dictionary values are arranged based on keys alphabetical order
my values and keys array contains :
myValueArray ={[orange,apple],
[ford,toyota,lexus]}
myKeyArray ={[fruits],[cars]}
I am adding keys and value to a NSMutabledictionary using
myDictionary = [[NSMutableDictionary alloc]initWithObjects:myValueArray forKeys:MainDelegate.myKeyArray];
myDictionary should be
myDictionary = { Fruits =(orange,apple);
cars =(ford,toyota,lexus);}
but it is added in key's alphabetical order and looks like
myDictionary = { cars =(ford,toyota,lexus);
Fruits =(orange,apple);}
is there a way to add key value pairs in dictionary as it is without any ordering.
I am trying this to populate a grouped uitableview. since keys are used as sections everything looks like contacts app where sections and its corresponding values are arranged alphabetically. But i need the recent section to be shown first(the first one in array).
Upvotes: 0
Views: 184
Reputation: 4163
If you need to conserve your initial order, then you have to use an NSMutableArray
.
NSMutableDictionary
is designed to be able to access the values for key in the fastest possible way, and having the key sorted helps with that.
Here is how to declare the dictionary and array and how to use them for a grouped tableView:
NSDictionary *myDictionary = @{ @"cars": @[@"ford" , @"toyota", @"lexus"], @"Fruits": @[@"orange", @"apple"]};
NSArray *keysArray = @[ @"Fruits", @"cars"];
// first section
NSString *sectionName = keysArray[0];
NSArray *sectionArray = myDictionary[sectionName];
// second section
sectionName = keysArray[1];
sectionArray = myDictionary[sectionName];
Upvotes: 2
Reputation: 3389
NSMutableDictionary
doesn't have any sorting associated to it, when you print this in log, it will display in sorting order.
You can manage a separate NSMutableArray
and put you key
in the order in which you want to fetch from NSMutableDictionary
.
That can be the easiest way to store values and fetch as per your requirement.
May this help you.
Upvotes: 0