How to reorder NSMutableDictionary to a NSMutableArray? - iphone

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.

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 access the index value from NSArray

I need to access the value of an NSArray by index. The following code crashes on line 3:
livevalues=[responseString JSONValue];
NSLog(#"%d",[livevalues count]);
NSString *objectvalue = [livevalues objectAtIndex:1];
NSLog(#"redyyyyyyyyyyy%#",objectvalue);
livevalues count is 4
livevalues array string is {"to": "INR", "rate": 53.801043700000001, "from": "USD", "v": 53.801043700000001}
I need values from that array is only 53.801043700000001 only
Use following expression
livevalues[1][#"rate"]
It is a Dictionary so Try like below
NSString *objectvalue = [livevalues objectForKey:#"rate"];
You have to use :
NSString *objectvalue = [[livevalues objectAtIndex:1] objectForKey:#"yourKey"];
to get the key for the desired string NSLog the description of the array and get your key from there
NSLog(#"%#",[livevalues description]);

NSJSONSerialization - key names from array

I am parsing JSON data using objective-c.
The data is as follows:
{"parcels":{"12595884967":{"kj_number":"KJ6612636902","recipient":"Krzysztof Racki","courier":"3"}}}
I have an object "parcels" which has keys for packages. Now while I dont have a problem extracting this using JSONSerialization class, I am stuck figuring how to get a key name (i mean, how to read value 12595884967 from code).
Code:
if ( [ NSJSONSerialization isValidJSONObject:jsonObject ] ) {
// we are getting root element, the "parcels"
NSMutableSet* parcels = [ jsonObject mutableSetValueForKey:#"parcels" ];
// get array of NSDictionary*'ies
// in this example array has single NSDictionary* element with flds like "kj_number"
NSArray* array = [ parcels allObjects ];
for ( int i = 0 ; i < [ array count ] ; ++i ) {
NSObject* obj = [ array objectAtIndex: i ];
// the problem: how i get this dictionary KEY? string value of 12595884967
// how I should get it from code here?
// like: number = [ obj name ] or maybe [ obj keyName ]
if ( [ obj isKindOfClass:[ NSDictionary class ] ] ) {
// this always evaluates to true
// here we do reading attributes like kj_number, recipient etc
// and this works
}
}
}
for example in java it was:
JSONObject json = response.asJSONObject();
JSONObject parcels = json.getJSONObject( "parcels" );
#SuppressWarnings("unchecked")
Iterator<String> it = parcels.keys();
while ( it.hasNext() ) {
String key = it.next(); // value of 12595884967
Object value = parcel.getObject( key ); // JSONObject ref with data
}
A set doesn't store keys. You want to get a dictionary from the json.
NSDictionary* parcels = [jsonObject objectForKey:#"parcels"];
// get the keys
NSArray *keys = [parcels allKeys];
for (NSString *key in keys) {
NSDictionary *parcel = [parcels objectForKey:key];
// do something with parcel
}
Getting the keys in an array first is optional, you could iterate over the parcels dictionary directly: for (NSString *key in parcels) {.
I would propose to use a NSDictionary instead of NSMutableSet.
The NSDictionary has a method allKeys that will provide you with the requested data.

Looping through a sorted dictionary un sorts it.

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.

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