How to update NSMutableDictionary? - iphone

I have an NSMutableDictionary.
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
I have to update an element in that dictionary. How i can do that?

Please refer to the API here
First retrieve the objects using
[dict objectForKey:#"key"];
Later, you can set them back using:
- (void)setObject:(id)anObject forKey:(id)aKey
- (void)setValue:(id)value forKey:(NSString *)key

dictionary only allows you to have one objects for each key so if you use "set object for key" it will update the current one

NSMutableDictionary's method addEntriesFromDictionary.
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/Reference/Reference.html
If both dictionaries contain the same key, the receiving dictionary’s previous value object for that key is sent a release message, and the new value object takes its place.

Related

How to retrieve String from NSDictionary in objective C?

I am trying to retrieve the value for a key in a NSDictionary. The dictionary has been initialised with key value pairs both of type string. The trouble is, I cannot seem to retrieve the value with I call objectForKey or valueForKey.
I am able to iterate over the dictionary and print both keys and values.
Can someone point out where im going wrong? Here is my code...
//Set up dictionary with options
keys = [NSArray arrayWithObjects:#"red", #"blue", nil];
values = [NSArray arrayWithObjects:#"1.7", #"2.8", nil];
conversionOptions = [NSDictionary dictionaryWithObject:values
forKey:keys];
Then this is called on the select row in a picker
NSLog(#"... %#", [keys objectAtIndex:row]); //prints out the key
NSString *theString = [keys objectAtIndex:row]; //save it as a string
NSLog(#"The string is... %#", theString); //print it out to make sure im not going crazy
NSLog(#"the value is : %#",[conversionOptions objectForKey:theString]); // I just get NULL here
//NSLog(#"the value is : %#",[conversionOptions valueForKey:theString]); // This doesn't work either, I just get NULL
You're creating a dictionary with an array as the only key and an array for its value! You want the dictionaryWithObjects:forKeys: (plural) factory, not dictionaryWithObject:forKey: (singular) so that each element of the keys array will be used as a distinct key for the respective element of the values array.
I find the dictionaryWithObjectsAndKeys: factory to be more useful most of the time, e.g.:
conversionOptions = [NSDictionary dictionaryWithObjectsAndKeys:#"1.7", #"red", #"2.8", #"blue", nil];
This is how you retrieve a string from a dictionary object
NSString * string = [dictionary objectForKey:#"stringKey"];
Use objectForKey: not valueForKey:.
Make sure conversionOptions is non-nil when you call objectForKey: (which is the right method).
And, yeah, derp -- I missed that the wrong factory method was used. You could do dictionaryWithObjects:andKeys: or do what pmjordan said said.
You absolutely must use objectForKey:, though. valueForKey: is specific to KVC.

Get the values from NSMutableDictionary inside NSMutableDictionary

I create two NSMutableDictionary: dictionary1 and dictionary2. In the first dictionary I store some array object having there keys. And in the second dictionary I store the object of first dictionary with the key like this:
int page = 1;
[dictionary2 setObject:dictionary1 forKey:[NSString stringWithFormat:#"%d",page]];
[dictionary1 removeAllObjects];
but at the time of retrieve of the object i do like this
dictionary1 = [dictionary2 valueForKey:[NSString stringWithFormat:#"%d",page]];
NSLog(#"dictionary1 %#", dictionary1);`
Then it gives null value. I don't know what mistake I do.
After you add dictionary1 to dictionary2, you are removing all of the objects.
This is the same dictionary that is in dictionary2 (it does not create a copy), therefore you are removing the objects from it as well.
You need to remove the line [dictionary1 removeAllObjects];.
Then, since you are done with dictionary1 at this point, you can either remove the reference to it or set to a nice new shiny dictionary which is ready to use:
// Remove the reference
dictionary1 = nil;
// Or, create a new, empty dictionary
dictionary1 = [[NSDictionary alloc] init];
Did you correctly alloc/init dictionary1 and dictionary2? Make sure the dictionaries themselves are not nil.
try this
dictionary1 = [dictionary2 objectForKey:[NSString stringWithFormat:#"%d",page]];

Setting value for nsmutabledictionary in multi levels

I am trying to set a key for UserName as with respect to this code:
{
"CustomerAccount":{
"UserName":"String content"
};
I am trying to set the username here, does anyone know how can I set a name in dictionary with levels?
My code is as:
[mutabledictionary setObject:self.uitextfield.text forKey:UserName];
however this sets the username below to CustomerAccount not insider CustomerAccount.
Any help here would be appreciated.
Thanks.
If the two level mutable dictionary already exists (its not clear from your question) you need to send your setObject:forKey message to the second level dictionary, like so:
[[mutabledictionary objectForKey:#"CustomerAccount"] setObject:self.uitextfield.text forKey:UserName];
You can just add a sub-dictionary, like this:
NSDictionary *userAccount = [NSDictionary dictionaryWithObject:#"String Content" forKey:#"UserName"];
NSMutableArray *accounts = [NSMutableArray arrayWithObject:userAccount];
// do something with accounts
NSLog(#"%#", accounts);
Just create create array of CustomerAccount and use in NSDictionary. Use
[NSDictionary dictionaryWithObjects:objects forKeys:keys];

Mutating method send to immutable object

This the snippet of code where I get an error:
//sourceArray is a NSMutablearray
NSMutableDictionary *dayOfWeekDictionary= [sourceArray objectAtIndex:indexpath.row];
[dayOfWeekDictionary setObject:[NSNumber numberWithBool:YES] forKey:#"isSelected"];//line 2
What I’ve come to know from googling is that there is some stuff in assigning immutable object into mutable object.
I get an error at line 2. Any suggestions?
If [sourceArray objectAtIndex:indexpath.row] returns an immutable dictionary, simply assigning it to a variable of type NSMutableDictionary * doesn’t automatically convert it to a mutable dictionary. You could write this instead:
NSMutableDictionary *dayOfWeekDictionary= [NSMutableDictionary dictionaryWithDictionary:[sourceArray objectAtIndex:indexpath.row]];
By using +[NSMutableDictionary dictionaryWithDictionary:], you get a mutable dictionary based on another dictionary (which can be either mutable or immutable). Note that you do not own this dictionary, hence you don’t have to release it. Also note that this is not the same dictionary object as the one stored in the array. If you need both the array and dayOfWeekDictionary to be the same dictionary, then you should add a mutable dictionary to the array.
Are you sure there is an instance of NSMutableDictionary in [sourceArray objectAtIndex:indexpath.row]?
I suggest placing a break point at line 2 and inspecting the content of dayOfWeekDictionary.
AND
In your comment, you set an instance of NSMutableArray into the variable dayOfWeekDictionary of type NSMutableDictionary, if you try to call [dayOfWeekDictionary setObject:[NSNumber numberWithBool:YES] forKey:#"isSelected"]; the application will crash with an unrecognized selector sent to instance.

Retrieving data from a NSDictionary

I am not quite sure I understand how to do the following.
If I wanted to add e.g. an author and a title (key, value) to a dictionary. Fill that dictionary with data, then have another dictionary for say e.g. k = genre v = artist name and fill it with data.
Then I want to add the dictionaries to an array.
Firstly how is that done? and secondly, what if I allow the user to log their own entries. So I have to textfields on screen, when the user is done, it stores the fields as key value pair in a new dictionary e.g. user's dictionary.
What will I do later when trying to fill a tableview with the users entered data, I dont know the keys or values in that dictionary so how could I retrieve that data?
I mean let's say I want to load the user's dictionary from array index 2 and fill a tableview's cells with each dictionary entry, how is this done? Maybe a method like on an array(get entry.title at index blah blah ), get Key value in dictionary?
How else can one actually get loaded user entered data that they arent aware of the values?
Regards
Add author and title to a dictionary (assuming they're objects that already exist - likely NSString instances in your case):
NSMutableDictionary *books = [[NSMutableDictionary alloc] initWithCapacity:10];
[books setObject:title forKey:author];
Same thing for genre/artist:
NSMutableDictionary *music = [[NSMutableDictionary alloc] initWithCapacity:10];
[books setObject:artist forKey:genre];
Then put them in an array:
NSArray *theArray = [NSArray arrayWithObjects:books, music, nil];
Then to read out the stuff at array index 2:
id key;
NSDictionary *theDictionary = [theArray objectAtIndex:2];
id value;
for (key in [theDictionary allKeys])
{
value = [theDictionary objectForKey:key];
// do something with the value
}
You can get an NSArray of keys in the dictionary using allKeys. Then you can retrieve the values using objectForKey:
for (id key in [myDict allKeys]) {
NSLog(#"key: %#, value: %#", key, [dictionary objectForKey:key]);
}