Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a value in NSDictionary in iPhone

I have a array (dataArray) of NSDictionary "item". It has datas like "david" for key "name" and "85" for key "marks" etc for 5 students. I want to replace the mark of david to 90 with respect to the array index value (ie 0 for dictionary containing david and 85). How can I do it?

The code for content in array is

[item setobject:name forkey:@"Name"]; [item setobject:mark forkey:@"Marks"]; [dataArray addOject:item] 

The above code goes inside parsing, so i have array with 5 objects (students), their name and marks, now I want to replace the mark of the first object in the dataArray.

like image 523
Warrior Avatar asked Dec 21 '10 16:12

Warrior


People also ask

How do you set a value in NSDictionary?

You have to convert NSDictionary to NSMutableDictionary . You have to user NSMutableDictionary in place of the NSDictionary . After that you can able to change value in NSMutableDictionary .

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys.

What is a NSDictionary object?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.


2 Answers

Here's what you can do:

NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init]; NSDictionary *oldDict = (NSDictionary *)[dataArray objectAtIndex:0]; [newDict addEntriesFromDictionary:oldDict]; [newDict setObject:@"Don" forKey:@"Name"]; [dataArray replaceObjectAtIndex:0 withObject:newDict]; [newDict release]; 

Hope this helps!

like image 117
donkim Avatar answered Sep 28 '22 04:09

donkim


You first need an NSMutableDictionary with it you can change the key and value.

It would be like this:

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"david", @"name", "85", @"marks", nil];  [dict setObject:@"90" forKey:@"david"]; 
like image 43
vodkhang Avatar answered Sep 28 '22 04:09

vodkhang