NSDictionary stores copy of redundant objects - how to prevent? - nsdictionary

I've build some code that makes an auxiliary dictionary to store the keys of the main dictionary. So I can get a key for a value. To make them unique, in case of two or more identical values, I store the IDs of the dictionary objects as keys and their keys as the objects.
But when two objects have the same value, they also have the same ID. Therefore I cannot retrieve two different keys:
NSDictionary *myDict = #{#"key1": #"obj1", #"key2": #"obj1", #"key3" : #"x"};
NSLog(#"%p",[myDict objectForKey:#"key1"]);
NSLog(#"%p",[myDict objectForKey:#"key2"]);
Output:
2013-03-06 02:03:28.740 DictTest[2855:303] 0x1000028e8
2013-03-06 02:03:28.741 DictTest[2855:303] 0x1000028e8
How can I prevent this?

To answer my own question: Its not an issue of the dictionaries, but of the string literals. #"obj1" always gives the same ID. To solve this problem, I have to setup the dictionary by:
NSDictionary *myDict = #{#"key1": [NSMutableString stringWithFormat:#"%#",#"obj1"], #"key2": [NSMutableString stringWithFormat:#"%#",#"obj1"], #"key3" : #"x"};
Note that "NSMutableString"! You will need mutable objects.

Related

JSONKit: how to keep order of JSON dictionary keys

I've some JSON String that represents a Map (Dictionary) from the server.
I need to draw this map as it is # my iPhone app.
I am using JSONKit and it seems that it uses Hashing function to insert keys into its internal JKDictionary....
So should I send a priority number to order the keys? Or there is some way to make JSONKit to preserve keys ordering of the server JSON data?
You can choose to add a order property to your dictionary. And sort your keys using that property. Then you can enumerate your dictionary using your sorted keys. enumerateKeysAndObjectsUsingBlock:
// Here I suppose you have added another number property `order` for your dictionary's values
NSArray *sortedKeys = [dic keysSortedByValueUsingComparator:^(id obj1, id obj2){
return [obj1 order] < [obj2 order];
}];
// for in will give your an ordered travel for your sortedKeys
for (id key in sortedKeys) {
// handle your dic
[dic objectForKey:key];
}
Dictionaries are not ordered, but arrays are, so if you can change your JSON data structure to an array, you should get an ordered result.
[{'key1':'value1'},{'key2':'value2'},{'key3':'value3'}]
What does your data look like?

Table View with Countries / States / Cities

I am downloading some information from a JSON feed about countries, states and their cities. The way I have my final data structure is as follows:
An NSArray where each element holds an NSDictionary. Each NSDictionary has a key of the name of the country, and a value of an NSDictionary corresponding to the states. Each of those NSDictionarys hold a key of the name of the state and a value of an array with a list of the names of the cities.
I want to display each country in a different section in a table view. To return the number of countries (aka. numbeber of sections), I can just do [countriesArray count].
However, to return the number of states and cities of each country, that seems impossible with my current structure. I can access [countriesArray objectAtIndex:index], but after that, how can I access the value of that dictionary (the key is the name of the country)?
Should I restructure my data structures? If so, what's the best way to sort this kind of data?
you may handle this problem using the collapsible tableview
from this you can display the relevant data as your requirement.
You can have below data structure which may help.
A container NSArray which has NSDictionary as its object.
Each dictionary has fixed keys like: countryName and stateInfo.
The value of this keys will be: string and NSDictionary.
Each stateInfo dictionary should have fixed keys like: stateName, cities
the value of this keys will be: string and NSarray of cities.
NSArray *countryKeys = [countriesArray allKeys]; //will return you an array of all keys(country names).
Also, instead of doing [countriesArray objectAtIndex:index], you should do [countriesArray valueForKey:[countryKeys objectAtIndex:index]];

iPhone: Duplication of key issues with NSMutableDictionary

I am getting an XML format data from server and parsing it in an scenario. I am having problem putting this data in key, value pair using NSMutableDictionary. Because, NSMutableDictionary key is unique. So, it overwrites the key with the previous value existing if there are same keys are coming from xml.
For ex: My XML data is below.
<?xml version='1.0' encoding='utf-8'?><order>
<number>123</number>
<detail>
<name>shoe</name>
<description>This is from nike</description>
<price>10.00</price>
<name>discount</name>
<description>This is from Arrow</description>
<price>-1.00</price>
<name>bag</name>
<description>This is a leather one</description>
<price>10.00</price>
</detail>
</order>
[appDelegate.finalOrderDict setObject:trimmString forKey:elementName];
I am trying to put the data in key, value pair using NSMutableDictionary, because, i'll be showing the output in another view like below.
Summary:
Shoe $ 10.00
Discount $ -1.00
Bag & 10.00
Discount $ -2.00
But, as the keys are repeating same, its overwriting the data from the existing one.
Could someone help me resolving duplicating of key in case if there are same keys present in the data and we try to put that in NSDictionary.
Thank you!
NSDictionary is behaving as intended - when -setObject:forKey: is called, an existing key-value pair is overwritten if the old key and the new key respond YES to -isEqual:. It sounds like you need to modify your data structure.
One idea would be having appDelegate.finalOrderDict instead be an NSArray of NSDictionary objects. Each NSDictionary would then have "name" and "price" key-value pairs.
You could also have each value promoted to an array if it already exists:
id existingValue = [appDelegate.finalOrderDict objectForKey:forKey:elementName];
if ([existingValue isKindOfClass:[NSMutableArray class]]) {
[existingValue addObject:trimmString];
} else if (existingValue) {
[appDelegate.finalOrderDict setObject:[NSMutableArray arrayWithObjects:existingValue, trimmedString, nil] forKey:elementName];
} else {
[appDelegate.finalOrderDict setObject:trimmedString forKey:elementName];
}
This approach is riskier, however, as you have to type-check all objects obtained from finalOrderDict, to see if they are strings or arrays.

Does array contain a specific value

I have an array of nsdictionaries and one key is ID (which is unique) I simply want to see if the the array of dictionaries contains a specific ID.
Really simple but its friday and after statiny up watching the election i think my brain is melting. Any help would be great.
Thanks
NSArray *arrayOfDicts = /*...*/ ;
for (NSDictionary *currentDict in arrayOfDicts)
if ([[currentDict valueForKey:#"ID"] isEqualToString:#"The ID you are searching for"])
// Do your stuff.

NSDictionary return value problem

i create a array from a NSDictionary object:
NSarray *myarray=[dictionary allValues];
however the return array object at index is not according to the dictionary, for instance the first object in dictionary was "title", but in my array it returned contact number, why this happended and how to prevent?
also when i set the object to my Dictionary it mess up the queue for instance:
[item setObject:#"title" forKey:#"title"];
[item setObject:#"1997" forKey:#"year"];
[item setObject:#"history" forKey:#"summary"];
but when i printed out this dictionary in console, the first object was become history, second become year, and last was title,how and why it could happen?am i miss anything thing i should now about NSDictionay, have anybody meet this problem before?
NSDictionary does not maintain order.
The NSArray is ordered, but its data comes from the un-ordered dictionary.
See also: NSDictionary with ordered keys
I have done maintain original order of NSDictionary.
Thanks to matt gallaghers orderedDictionary class