How to change one value in NSMutableDictionary - ios

I have a NSMutableDictionary with one key and it has the following values.
How can I change the value in item2 from 1 to 0? That's the only change I need.
The only way I have found is to recreate this whole key from scratch, change that one value and then delete that key and replace it with a new one. Is there any easier solution than that?

I will assume you get dict as an instance of NSMutableDictionary somehow:
NSMutableArray *tmp = [dict[#"07:00 AM.infoKey"] mutableCopy];
tmp[2] = #"0";
dict[#"07:00 AM.infoKey"] = tmp;
Unfortunately with nested arrays in dictionaries, the arrays aren't automatically mutable so there isn't any better method to doing so, like you observed.

Related

how to parse a dictionary inside an array, which is in a dictionary

In my JSON response i receive a dictionary, which has a array, inside that array is a dictionary with few key-values, to make it simple to understand here is the JSON response:
{
weather = (
{
description = haze;
icon = 50n;
id = 721;
main = Haze;
}
);
}
I want to know how can i retrieve the elements description, icon, id and main. Suppose i have a NSString called str, how can i add the value of description to this string. I have tried many different things, but none seem to work. The one i thought should work, but didn't is:
str = [[[dir valueForKey:#"weather"] objectAtIndex:0] valueForKey:#"description"];
Can someone let me know how can i access those 4 values. I don't want to create a new array of those values and then retrieve them. Regards.
Use NSJSONSerialization to convert your JSON data to NSObjects.
Then you need to index into your objects based on their structure.
If the structure is fixed, and guaranteed, you can do it with fixed indexes/keys:
//data in theJSONDict.
NSArray *outerArray = theJSONDict[#"weather"];
NSDictionary *firstWeatherItem = outerArray[0];
NSString *firstItemDesc = firstWeatherItem[#"description"];
You could also do it all in 1 line:
firstItemDesc = theJSONDict[#"weather"][0][#"description"];
But that is much harder to debug.
If this is JSON data coming from a server you need to code more defensively than above, and write code that tries to fetch keys from dictionaries, tests for nil, and either loops through the array(s) using the count of objects, or tests the length of the array before blindly indexing into it. Otherwise you'll likely crash if your input data's format doesn't match your assumptions.
(BTW, do not use valueForKey for this. That is KVO code, and while it usually works, it is not the same as using NSArray and NSDictionary methods to fetch the data, and sometimes does not work correctly.)

Dont add NSMutabledictionary values in alphabetical order

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).
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];
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.

NSMutable dictionary not working properly

I am developing an iPad application and for this application I have one function as below :-
-(void)testcurrentest:(NSMutableDictionary *)keydictionary{
NSArray *allKeys = [keydictionary allKeys];
if ([allKeys count] > 0) {
for(int i = 0;i< allKeys.count;i++){
[_currenies removeAllObjects];
NSString *product = [NSString stringWithFormat:#"%#", [keydictionary objectForKey:allKeys[i]]];
int kl = [productPriceSeasonCode intValue];
for(int i =0;i<kl;i++){
[_currenies addObject:#"0"];
}
NSLog(#"................%#",_currenies);
[_currencydictionary1 setObject:_currenies forKey:allKeys[i]];
NSLog(#"full dictionary...%#",_currencydictionary1);
}
}
}
Here, NSLog print the currencies array based on the kl integer values but when I'm trying to set the NSMutableDictionary the currencies but mutable array always show the latest array values.
You are using the same array for all values, they should be unique objects if you don't want change of one value to affect the other values. Initialise _currenies on every loop step or use its deep copy when preparing a new object.
A bit of code:
[_currenies removeAllObjects]; // < The same array you've added to dict on previous loop steps
Creating a new array at each loop step would create a unique object for all key-value pair:
_currenies = [NSMutableArray array]; // < Note it is not retained, apply memory management depending on your project configuration
Your code is a garbled mess. As others have pointed out, you are using the same loop index, i, in 2 nested loops, making it very hard to tell your intent. Don't do that, ever. It's horrible programming style.
You are also creating a string "product" that you never use, and fetching the same integer value of productPriceSeasonCode on every pass through the outer loop. I suspect you meant to fetch a value that varies with each entry in your keydictionary.
Then, you have an array, _currenies, which you empty on each pass through your outer loop. You then add a number of "0" strings to it, set a key/value pair in your _currencydictionary1 dictionary to the contents of that array, and then repeat. Since you re-use your _currenies array each time, every key/value pair you create in your _currencydictionary1 dictionary points to the exact same array, which you keep changing. At the last iteration of your outer loop, all the entries in your _currencydictionary1 will point to your _currenies array, which will contain the last set of contents you put there.
Create a new array for each pass through your outer array, and add that newly created array to your _currencydictionary1. You want a unique array in each key/value pair of your _currencydictionary1.
In short, NSMutableDictionary is working just fine. It's your code that isn't working properly.
Not an answer but comments don't have formatting.
The question should provide more information on the input and desired output.
First simplify your code and it should be easier to find the error:
-(void)testcurrentest:(NSMutableDictionary *)keydictionary{
NSArray *allKeys = [keydictionary allKeys];
for(NSString *key in allKeys) {
[_currenies removeAllObjects];
int kl = [productPriceSeasonCode intValue];
for(int i =0; i<kl; i++){
[_currenies addObject:#"0"];
}
NSLog(#"................%#",_currenies);
_currencydictionary1[key] = _currenies;
NSLog(#"full dictionary...%#",_currencydictionary1);
}
}
Note: product was never used.

How to turn UITextField user input into a usable pointer to a dictionary key?

I am trying to take a user input in a UIText field and turn it into a pointer that will access a dictionary key and then return the corresponding value for use in an equation. I feel like I am in the ballpark but I can't figure out how to make it work.
The keys are going to be float values, and the user input is the key itself. I realize that sounds confusing. Here's an example: The user inputs 44.25 in the UITextField. I need this user input to find the 44.25 key in my dictionary and then return the corresponding value associated with that key that will then plug into a simple equation.
Here is my code calling the dictionary (which works) and my attempt at making a pointer out of the input, which does not work.
Thanks in advance for your help.
NSString *path = [[NSBundle mainBundle] pathForResource:#"myDictionary" ofType:#"plist"];
NSDictionary *myDictionary = [NSDictionary dictionaryWithContentsOfFile: path];
float inches = [self.inchesText.text floatValue];
NSLog(#"%.2f", apples);
NSLog(#"There are %# oranges", MyDictionary [apples]);
Just take the text from your text field and use it in a call to ojectForKey. Make sure you code for the (likely) case where the user-entered key can't be found in the dictionary and you get back a nil.
The code is dirt simple, and might look something like this:
NSString *key = self.inchesText.text;
NSString *value = myDictionary[key];
if (value == nil)
//Tell the user they entered an invalid key
else
//Do whatever you need to do with the fetched value.
As far as I know all keys for NSDictionaries need to be objects, not primitives. That being said you could create an object around your primitive with NSNumber objects.
I don't think that would help you though. Since you are reading the NSDictionary straight from file I would assume they are being read into the Dictionary as NSString values (#"44.25" instead of the number 44.25). If that is the case then you could just pass the pointer to the textfield.text to retrieve your desired Dictionary element (assuming the text is equal to one of your dictionary keys in the file).

Saving IOS dictionary with arrays as keys

i am working with Tapku's Calendar, and i want to save some values that will be user inputed.
But i am kind of stumbled on how i would achive this, here is the layout:
// allocate the arrays and dictionary
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableArray *dateValueArray = [[NSMutableArray alloc] init];
// set array values
[dateValueArray addObject:#"first string"];
[dateValueArray addObject:#"Second string"];
// set dictionary with date as key, and array as value
[dict setObject:dateValueArray forKey:testdate];
The dictionary dict, will be the only Dictionary, but since that dictionary uses arrays for objects, i would have multiple arrays.
So, lets say there are multiple dates registerd in "dict", different keys would have to use different arrays? Sorry i am abit confused my self here.
Is there any way i can use 1 array to store all the strings associated with different dictionary keys ?
EDIT 1
Elaboration:
The whole idea is that the user can input text that are associated with dates.
I will need to store these values and i will need to store which date they are associated to.
So i have multiple values in an array, associated with 1 date in a dictionary.
And keeping in mind that i will have to store this, i would like to know how i should assign the values to the dates.
EDIT 2:
Basically what i need for the Array is something like AddObject ForKey
Edit 3
More elaboration::
Basically i want to access the values in this manner:
[date1][note1]
[date1][note2]
[date2][note1]
[date2][note2]
And the amount of values in both date and note are variable.
If I understand what you are asking about, what you want is the property of NSDictionary allKeys which is an array of all the keys in that dictionary.
Now I see your edit. You are in the right way. To perform what you are looking for, do something like this:
First, allocate your dict somewhre:
// allocate the arrays and dictionary
NSMutableDictionary *dict = [NSMutableDictionary new];
Now, everytime you get a new date with a new string, first check if there's the first string for that date. If yes, create a new array. If not, add your string inside the previously array.
NSMutableArray *valuesForDate = dict[givenDate];
if (!valuesForDate)
{
valuesForDate [NSMutableArray new];
dict[givenDate] = valuesForDate
}
[valuesForDate addObject:#"first string for dateGiven"];
[valuesForDate addObject:#"Second string for dateGiven"];
Now you can retrieve the values with something like you wanted:
NSString *test = dict[date1][0]; //first string associated for date1
NArray *allStringsForDate2 = dict[date2]; //array with all the strings for date2
You can try using NSMapTable instead of NSDictionary, which is much more flexible but also much harder to use. You'll also find it hard to find anyone knowing the answers if you have questions about NSMapTable. But you can definitely create an NSMapTable which will use pointers of objects as keys, instead of the values.

Resources