Looping through a sorted dictionary un sorts it. - iphone

I have a dictionary that I have sorted. My problem is when I loop through it gets unsorted again.
//sort the poiIDArray so it appears alphabetically
NSArray *sortedValues = [[self.pois allValues] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSMutableDictionary *orderedDictionary=[[NSMutableDictionary alloc]init];
for(NSString *valor in sortedValues){
for(NSString *clave in [self.pois allKeys]){
if ([valor isEqualToString:[self.pois valueForKey:clave]]) {
[orderedDictionary setValue:valor forKey:clave];
}
}
}
NSLog(#"ordered dic: %#",orderedDictionary);
//loop through dic and get names.
for(NSString *key in orderedDictionary) {
NSLog(#"%#",key);
}
Here is my log.
2012-10-26 11:49:35.221 CPOP Test 4[1277:c07] ordered dic: {
"Badger Burgers" = 5;
"Costa Coffee" = 4;
"Spiffing Drinks" = 6;
"Vals Vegetables" = 7;
}
2012-10-26 11:49:35.221 CPOP Test 4[1277:c07] Costa Coffee
2012-10-26 11:49:35.222 CPOP Test 4[1277:c07] Spiffing Drinks
2012-10-26 11:49:35.222 CPOP Test 4[1277:c07] Badger Burgers
2012-10-26 11:49:35.222 CPOP Test 4[1277:c07] Vals Vegetables
Can anyone tell me why this is happening and how to fix it?

Dictionaries are by definition unordered. If you need a particular order, use an array.

Related

How to match the id's to names iphone?

I am getting Names and ID's from DB... and storing those values in Array... Like Names storing in NamesArray and ID's storing in IDsArray...
Example:
NamesArray - {Peter, Arnold, John,Samuel}
IDsArray - {1, 2, 3,4}
After getting those values from DB... I am sorting NamesArray... It will come like this...
NamesArray Value - {Arnold,John,Peter,Samuel}
How to change the IDsArray according to the NamesArray?
The same scenario is needed for Search functionality....
Example:
I am searching 'P' text in SearchBar... It will show 'Peter' in TableView...
How to get the IDs from idarray according to the Searched Text?
Thanks in advance
You could use an array of dictionaries with keys Name and ID. After you could use NSPredicate for your search and NSSortDescriptor for sorting
yourArray: (
{
id = 1;
name = Peter;
},
{
id = 2;
name = Arnold;
},
{
id = 3;
name = John;
},
{
id = 4;
name = Samuel;
});
Sort
nameDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
nameDescriptors = [NSArray arrayWithObject:nameDescriptor];
sortedArray = [yourArray sortedArrayUsingDescriptors:nameDescriptors];
Filter
NSString *strToFilter = #"P";
NSArray *filteredNames = [yourArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(name BEGINSWITH[c] %#)", strToFilter]];
For this scenario simple logic can be done.
NamesArray - {Peter, Arnold, John,Samuel}
IDsArray - {1, 2, 3,4}
Have the searched names in separate array which will not affect NamesArray when you search.
searchedNamesArray - {Peter}
after that get the index of the searched object from array
for (NSString *value in searchedNamesArray)
{
NSInteger index = [NamesArray indexOfObject:value];
// you will get the index of the object from which you can use from getting the id from IDsArray
NSLog(#"ID - %#", [IDsArray objectAtIndex:index]);
}

How to reorder NSMutableDictionary to a NSMutableArray?

I have a NSMutableArray containing NSURLConnection descriptions, like so:
array {
"<NSURLConnection: 0x60eb40>",
"<NSURLConnection: 0x6030e0>",
"<NSURLConnection: 0x602ce0>",
"<NSURLConnection: 0x60c330>",
"<NSURLConnection: 0x662f5a0>",
}
I have also a NSMutableDictionary whose keys are the items from the above NSMutableArray, like so:
dictionary {
"<NSURLConnection: 0x602ce0>" = "Last update: Sep 3, 2012";
"<NSURLConnection: 0x6030e0>" = "Last update: Sep 7, 2012";
"<NSURLConnection: 0x60c330>" = "Last update: Sep 4, 2012";
"<NSURLConnection: 0x60eb40>" = "Last update: Sep 6, 2012";
"<NSURLConnection: 0x662f5a0>" = "Last update: Sep 5, 2012";
}
I need to reorder the NSMutableDictionary to match the same order of the NSMutableArray indexes. Right now I'm doing like this:
int a;
for (a=0; a<self.array.count; a++) {
NSString *key = [self.array objectAtIndex:a];
NSString *object = [self.dictionary objectForKey:key];
if (object !=nil) {
[self.array removeObjectAtIndex:a];
[self.array insertObject:object atIndex:a];
}
}
Is there a better way to reorder this NSMutableDicitioanry to match the order of the NSMutableArray ?
Thank you!
NSDictionary 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 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.

Sorting of NSDictionary by amount of children per key

After searching the developer docs, google and other sites I still can't find how to accomplish the following...
I would like to sort a NSDictionary by the amount of values (i.e. count) per key. Do I need to use a custom NSSortDescriptor and if so, I would really appreciate some help with the code. Below is an example of the NSDictionary I would like sorted.
2 ways I would like to be able to sort dictionary:
1) Sort it so that the key "Australia" comes first because it has 3 cities, then USA with 2 cities, and finally UK with 1 city?
2) For a bonus I would also love to have the option to sort by the amount of objects i.e. Australia first with 6 objects, then UK with 4 objects (even though only 1 city) then USA with 2 objects.
"United Kingdom" = {
"City 1" = {
1 = "Object A";
2 = "Object B";
3 = "Object C";
4 = "Object D";
};
};
"Australia" = {
"City 1" = {
5 = "Object E";
6 = "Object F";
7 = "Object G";
};
"City 2" = {
8 = "Object H";
9 = "Object I";
};
"City 3" = {
10 = "Object J";
};
};
"United States of America" = {
"City 1" = {
11 = "Object K";
};
"City 2" = {
12 = "Object L";
};
};
Assuming you do store arrays in the dictionary you could do something like this:
NSComparator sorter = ^NSComparisonResult(id a, id b)
{
NSArray* a1 = a;
NSArray* a2 = b;
if([a1 count] > [a2 count]) return NSOrderedAscending;
if([a1 count] < [a2 count]) return NSOrderedDescending;
return NSOrderedSame;
}
NSArray* ordered = [dictionary keysSortedByValueUsingComparator:sorter];
Then in the "ordered" array you'll get the keys to the dictionary in the order of increasing number of elements in the arrays stored in the dictionary.
A NSDictionary is a Key—Value collection. It is not sortable. You will have to convert it to a NSArray (of NSArrays) instead.
For NSArray you will find several ways to do sorting:
with SortDescriptors
with Comparator-Blocks
with selector (methods)
with (C)-Functions

Extract the values from NSMutableDictionary

(
{
dateVal = "nov 26, 2010";
price = "1 - 195 kr";
},
{
dateVal = "nov 26, 2010";
price = "425 - 485 kr";
},
{
dateVal = "nov 26, 2010";
price = "415 - 640 kr";
})
How can i extract this NSMutableDictionay?
Help me!
You have plenty of choices (I suggest looking into NSArray class reference)
To get dictionary at specific index (whether dictionary you get is mutable or not depends, I think, on how have you created them and put them in array)
// make sure that index is in array bounds
NSDictionary* dict = [yourArray objectAtIndex:index];
NSLog(#"%#", [dict objectForKey:#"dateVal"]); // log date
NSLog(#"%#", [dict objectForKey:#"price"]); // log price
If you want to iterate through all dictionaries you have then you can use fast enumeration:
for (NSDictionary* dict in yourArray){
...
}
It seems to be an Array which contains Dictionnary.
But Vladimir is right, how did you get this ?
To get an item from a Dictionnary, use this :
[ dictionnary objectForKey:#"keyName" ];
Do you mean converting from this string to NSDictionary? It looks like a JSON String for me, doesn't it?
If it is a JSON String and you want to convert to a NSDictionary, you may want to use TouchJSON, some tutorial here

Obj-C / iPhone: NSArray question

I have an array that looks like this when printed via NSLog:
{
response = "Valid";
updates = (
{
string = "test";
integer = 3493;
},
{
string = "test2";
integer = 55454;
}
);
start-index = 0;
My question is how I can loop through through the "updates" array so that I may print the values for each "string" respectively.
Should be an easy "for" loop or something?
Dave
Assuming you NSLogged data has a type of NSDictionary with name data.
NSArray *updates = [data objectForKey:#"updates"];
for (NSDictionary *update in updates) {
NSLog(#"Update: %# - %#", [update objectForKey:#"string"], [update objectForKey:#"integer"]);
}