I am facing very strange problem in NSMutableDictionary. Please see the below code.
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:#"India" forKey:(#"Title")];
[dict setValue:#"Done" forKey:(#"Status")];
When I had printed this dictionary object, It shows like below.
{
Status =Done,
Title=India;
}
This keys getting shuffled, actually Title key should come first.
So, How can I resolve this issue.
That's not an issue.
You have mis understood or you'r getting wrong the NSDictionary. NSDictionary is a container to store values base on the keys.
So, there is no need of any order or indexing.
Reason behind is that you can only access container value if you know the key. So it is meaning less to check order of that keys. Because any how you have to use that key to access related value.
Now about order - Use NSArray instead and more of that use NSArray with object of NSDictionary. So that you have order with dictionary support.
Still the way to sort dictionary keys is below:
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:#"India" forKey:(#"Title")];
[dict setValue:#"Done" forKey:(#"Status")];
NSArray *keys = [dict allKeys];
keys = [keys sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSLog(#"%#",keys);
NSDictionary or NSMutableDictionary does not guarantee any ordering of it's key/value pairs. There's no way to keep your keys/values in a set order and it doesn't make sense for NSDictionary or NSMutableDictionary to work like this. (You use keys not indexes to retrieve values).
If you want your values or keys in a certain order for display purposes you can sort them after retrieving them:
NSArray * sortedKeys = [ [ myDictionary allKeys ] sortedArrayUsingSelector:... ] ;
or
NSArray * sortedKeys = [ [ myDictionary allKeys ] sortedArrayUsingComparator:... ] ;
You could then retrieve the associated objects for the sorted keys if you wanted.
Another option is to maintain 2 separate arrays, one for keys and one for values and keep them in order.
Related
So I have this NSDictionary like so:
NSDictionary *productionSchedule = [[[NSMutableDictionary alloc]initWithDictionary:[[areaData GetProductionScheduleData:communityDesc] objectForKey:#"Root"]] autorelease];
The data for the NSDictionary is coming from an API and due to the fact that NSDictionary does not do ordering, the order of the data in API is different in the NSDictionary, so now I am trying to put the keys of the NSDictionary into an NSMutableArray to handle the ordering. In my NSDictionary I have a value called SortOrder and I am trying to put the data in NSDictionary into NSMutableArray based on this value SortOrder (I have about 389 items and the SortOrder goes from 0 - 389) How would I do this?
I have this screenshot that will show you what my data is like:
What I am trying to do is put the key 'V3C0183' but as the 82nd item (there will be 81 items before this)
I am assuming I will have to do a foreach loop like so:
NSMutableArray *prodSchedSortedKeys
for(int i = 0;i<[productionSchedule count];i++)
{
[prodSchedSortedKeys addObject: ? ];
}
I just dont know what the next step would be to add an object based off the sort order....please help.
NSDictionary *dic = //your dictionary;
NSArray<NSDictionary *> *values = dic.allValues;
[values sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return [obj1[#"SortOrder"] integerValue] > [obj2[#"SortOrder"] integerValue];
}];
Now the dic is ordered.
But this is not the best solution of this problem. Server's data should be ordered instead, that the key like "VC31083" should in the key-value pairs too.
Edit1: sortedArrayUsingComparator: is used for normal sort of array, the performance isn't very well if the content is too large. Especially in this compare, it do addition actions: get value from dictionary, transform NSString to int, and then compare. You can Log to see how much time it spend on this sort with your data.
NSMutableDictionary/NSDictionary can't do that. Take a look at e.g. Matt Gallaghers OrderedDictionary.
Also take a look at this answer:
Getting NSDictionary keys sorted by their respective values
I would like some help sorting an NSArray of NSDictionary values based on each objects ISV key.
This is the code I have so far for creating my array objects so you have a better idea of what I am trying to do.
NSArray *combinedKeysArray = [NSArray arrayWithObjects:#"HASM", #"ISL", #"ISV", nil];
valuesCombinedMutableArray = [NSMutableArray arrayWithObjects:[dict objectForKey:#"HASM"],
[dict objectForKey:#"ISL"],
[dict objectForKey:#"ISV"],
nil];
combinedDictionary = [NSDictionary dictionaryWithObjects:valuesCombinedMutableArray
forKeys:combinedKeysArray];
[unSortedrray addObject:combinedDictionary];
// how do I then sort unSortedArray by the string values in each object ISV key?
any help would be greatly appreciated.
This can solve your problem
How to sort an NSMutableArray with custom objects in it?
https://stackoverflow.com/a/805589/1294448
You can use NSSortDescriptor to sort NSArays
Then in NSArray you have a method called sortedArrayUsingDescriptors
Or NSComparisonResult ca also be helpful some time http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/doc/uid/20000138-BABCEEJD
you won't be able to sort unSortedArray because it will only have one element in it (ie in your last line of code you are adding a single object by addObject).
That said, you cannot sort the dictionary either.. b/c dictionaries are unsorted by definition.
you can iterate over the keys of the dictionary in a specific order though, you can sort an array containing the keys of the dictionary.
NSArray *keys = [theDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingSelector:#selector(compareMethod:)];
You can use -sortedArrayUsingComparator: to sort any way you need.
[unSortedrray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *dict1, NSDictionary *dict2) {
return [[dict1 objectForKey:#"ISV"] localizedCompare:[dict2 objectForKey:#"ISV"]];
}];
I'm communicating with an API that sends back an NSDictionary as a response with data my app needs (the data is basically a feed). This data is sorted by newest to oldest, with the newest items at the front of the NSDictionary.
When I fast enumerate through them with for (NSString *key in articles) { ... } the order is seemingly random, and thus the order I operate on them isn't in order from newest to oldest, like I want it to be, but completely random instead.
I've read up, and when using fast enumeration with NSDictionary it is not guaranteed to iterate in order through the array.
However, I need it to. How do I make it iterate through the NSDictionary in the order that NSDictionary is in?
One way could be to get all keys in a mutable array:
NSMutableArray *allKeys = [[dictionary allKeys] mutableCopy];
And then sort the array to your needs:
[allKeys sortUsingComparator: ....,]; //or another sorting method
You can then iterate over the array (using fast enumeration here keeps the order, I think), and get the dictionary values for the current key:
for (NSString *key in allKeys) {
id object = [dictionary objectForKey: key];
//do your thing with the object
}
Dictionaries are, by definition, unordered. If you want to apply an order to the keys, you need to sort the keys.
NSArray *keys = [articles allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingSelector:#selector(compare:)];
for (NSString *key in sortedKeys) {
// process key
}
Update the way the keys are sorted to suit your needs.
As other people said, you cannot garantee order in NSDictionary. And sometimes ordering the allKeys property it's not what you really want. If what you really want is enumerate your dict by the order your keys were inserted in your dict, you can create a new NSMutableArray property/variable to store your keys, so they will preserve its order.
Everytime you will insert a new key in the dict, insert it to in your array:
[articles addObject:someArticle forKey:#"article1"];
[self.keys addObject:#"article1"];
To enumerate them in order, just do:
for (NSString *key in self.keys) {
id object = articles[key];
}
I am trying to get an array of all my keys in my NSDictionary into an array, and sorted using localizedCaseInsensitiveCompare. I first tried doing:
NSArray *test = [myDict keysSortedByValueUsingSelector#selector(localizedCaseInsensitiveCompare:)]];
I kept getting NSCFNumber localizedCaseInsensitiveCompare:]: unrecognized selector. I double checked and all of my 2 keys (for now) are strings.
I had to switch to doing to make it work:
NSArray *items = #[[[languages allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)]];
Why is that?!
Thanks!
There is different sorting in this two cases.
NSArray *test = [myDict keysSortedByValueUsingSelector#selector(localizedCaseInsensitiveCompare:)]];
this variant sort (from docs):
Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values.
You try to get an array, where you firstly sort values using your selector and then get list of keys. I guess, your dictionary's objects are not NSString and they don't know anything about this selector.
NSArray *items = #[[[languages allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)]];
Here you do right. You get the array of keys (which are NSString) and then sort it using right selector.
Because is keysSortedBy**Value**UsingSelector and that's why you get NSNumber exception,because is sorting by value , not by key, you have NSNumbers as values.
keysSortedby **Value** usingSelector...
I have a case where I need to have NSMutableDictionary with NSManagedObject as the key.
Based on this post, I can set NSManagedObject as key in dictionary by:
[NSValue valueWithNonretainedObject:]
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:product forKey:[NSValue valueWithNonretainedObject:category]];
How can I get back the value of dict? I've tried using NSValue again but it crash with no description.
Try using [theValue nonretainedObjectValue]
But if you want to access the keys frequently, a dictionary might not be the right data structure for you. Especially if you want some kind of inverse relationship with objects and keys (if that is what you mean with get back the value of dict).