If I have an NSMutableArray that looks like this:
self.securityQuestionsMutableArray = [[NSMutableArray alloc] init];
// This is how I would add an object or objects to a `NSMutableArray`
//[self.securityQuestionsMutableArray addObject:#""];
{
answer = "";
description = "ID Number";
displayText = "ID Number";
fieldName = IDNumber;
secuityQuestionId = 1;
},
{
answer = "";
description = "Test Question";
displayText = "Test Question";
fieldName = "Test Questionr";
secuityQuestionId = 2;
}
How can I add an object or objects in valueForKeyPath#"answer" valueForKeyPath NSMutableArray
to my existing NSMutableArray
You can set the values of individual NSMutableDictionary objects key-value pair like this
[[self.securityQuestionsMutableArray objectAtIndex:index] setValue:#"new Value" forKeyPath:#"answer"];
Here index will point to the specific object inside array. But remember all the objects inside the array should be of mutable dictionary type. If you use NSDictionary object, this will crash.
Related
I have a NSMutableDictionary to which I want to change the value of an element.
//My dictionary:
{
objectId = 8ED998yWd1;
cardInfo = {
state = published; //THIS!
price = 40;
color = red;
}
};
I have tried several ways, but the value does not change, like this:
[dictionary setObject:#"reserved" forKey:#"state"]; //nope
or this:
[dictionary setValue:#"reserved" forKeyPath:#"cardInfo.state"]; //nope
or that:
[[dictionary objectForKey:#"cardInfo"] setObject:#"reserved" forKey:#"state"]; //no
and this:
[dictionary setObject:#"reserved" forKey:[[dictionary objectForKey:#"cardInfo"] objectForKey:#"state"]];
How can I change the object "state" from "published" to "reserved"?
Thank you!
Assuming that both dictionary and cardInfo are NSDictionary instances:
You could get a mutable copy of the nested dictionary, modify the appropriate value, and write the modified dictionary back into the "top level" dictionary, like so:
NSMutableDictionary *mutableDict = [dictionary mutableCopy];
NSMutableDictionary *innerDict = [dictionary[#"cardInfo"] mutableCopy];
innerDict[#"state"] = #"reserved";
mutableDict[#"cardInfo"] = innerDict;
dictionary = [mutableDict copy];
I guess you could squeeze that in one line, but it would be one ugly line.
Edit:
If both the outer and inner dictionary were already mutable that would simplify things a bit, of course:
NSMutableDictionary *innerDict = dictionary[#"cardInfo"];
innerDict[#"state"] = #"reserved";
dictionary[#"cardInfo"] = innerDict;
I have NSArray of NSDictionaries which is coming from server as JSON format. I want to add one more NSDictinoary to the NSarray of NSdictionaries. Nsdictionary is based on key value pair. This is the response which I am getting. I want to add another dictionary of same format into "table". Pls Help..
Thanks in advance..!!
Table = (
{
Name = “xyz”;
Recordid = 3;
prefrenceorder = 1;
},
{
Name = “ABC”;
Recordid = 2;
prefrenceorder = 2;
},
{
Name = “swe”;
Recordid = 450;
prefrenceorder = 3;
},
{
Name = “asd”;
Recordid = 451;
prefrenceorder = 4;
}
);
As the NSArray coming from server is immutable so you need to create a new instance of NSMutableArray to add your own dictionary with the response coming from server.
NSMutableArray *newTable = [NSMutableArray arrayWithArray:Table];
[newTable addObject:your_new_dictionary];
Put the NSDictionary's into a NSMutableArray. And then from your instance add your new object NSDictionary
i.e
//The array which has your NSDictionary objects
NSArray *array;
//Putting this array into mutable one in order to add and delete elements
NSMutableArray *mArray = [array mutableCopy];
//Your custom object that you want to add
NSDictionary *yourObject;
//Add it to the array and voila
[mArray addObject:yourObject];
It is better not to convert immutable array to a mutable but to use appropriate NSJSONSerialization option - NSJSONReadingMutableContainers
Specifies that arrays and dictionaries are created as mutable objects.
NSMutableArray *mutableArray = [NSJSONSerialization JSONObjectWithData:yourData options:NSJSONReadingMutableContainers error:nil];
[mutableArray addObject:yourNewDictionary];
I am looping through an array, getting two items and putting them in a dictionary, and then add them to an array, but it keeps adding the last item of the array for the number objects in the array, even though when I log the dictionary inside the loop it has the correct value. Here is my code
for (TFHppleElement *element in nodesArray) {
[nameAndHrefDict setObject:[element objectForKey:#"href"] forKey:#"href"];
[nameAndHrefDict setObject:[element text] forKey:#"name"];
NSLog(#"PRE: %#", nameAndHrefDict);
[arrayOfDicts addObject:nameAndHrefDict];
NSLog(#"IN: %#", arrayOfDicts);
}
In the log I see this
PRE: {
href = "/dining-choices/res/index.html";
name = "Commons Dining Hall";
}
IN: (
{
href = "/dining-choices/res/index.html";
name = "Commons Dining Hall";
}
PRE: {
href = "/dining-choices/res/sage.html";
name = "Russell Sage Dining Hall";
}
IN: (
{
href = "/dining-choices/res/sage.html";
name = "Russell Sage Dining Hall";
},
{
href = "/dining-choices/res/sage.html";
name = "Russell Sage Dining Hall";
}
)
What is happening?
But it add the last value of nodesArray 8 times, instead of each value, why?
Thanks for the help in advance.
Please try:
for (TFHppleElement *element in nodesArray) {
[arrayOfDicts addObject:[NSDictionary dictionaryWithObjectsAndKeys:[element objectForKey:#"href"], #"href", [element text], #"name", nil]];
}
Objects are added to arrays by reference. The array doesn't create a copy of the dictionary, it just keeps a record of which dictionary has been added. You're adding the same dictionary, nameAndHrefDict, to the array every time. So the array considers itself to hold the same object multiple times.
At each iteration you are changing the value of that object but it is still the same object.
So the underlying issue is identify versus value. An array is populated by identity. You're expecting it to populate by value.
To fix: copy the dictionary when you add it to the array, or just create a brand new dictionary from scratch each time.
You need to alloc and init the array each time, so that there is new memory for it and then it wont add the same array 8 times
You have to instantiate the dictionary in the loop : see the code
NSMutableArray *saveData = [[NSMutableArray alloc]init];
for (int i=0; i<records.count; i++) {
RecordTable *record = [records objectAtIndex:i];
NSString *addID = record.addr_id;
NSMutableDictionary *saveToDic = [[NSMutableDictionary alloc]init];
[saveToDic setValue:addID forKey:#"addr_id"];
[saveData addObject:saveToDic];
}
I have a NSArray With NSMutableDictionary object inside this array like the following .What i want to get an object say at index:2 of this array and add that NSMutableDictionary object from the following array into other NSMutableDictionary already have say five elements at positions 6:
(
{
eventId = 2;
eventName = "Sweels ";
},
{
eventId = 1;
eventName = "Lakenge";
},
{
eventId = 23;
eventName = "Royta";
}
)
I am able to get the NSMutableDictionary object and and can extract the key and value and then can add but want to add whole object without extracting the key and values
{
eventId = 23;
eventName = "Royta";
}
You can initialize an NSMutableDictionary object with the keys and values contained in another given dictionary using this initializer:
- (instancetype)initWithDictionary:(NSDictionary *)otherDictionary
Example:
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] initWithDictionary:extractedDict];
If You do not want to create a new NSMutableDictionary Object and just need to add Key/Values to an existing Object then Use this Method:
- (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues
Example:
[newDict setValuesForKeysWithDictionary:extractedDict];
If you want all the values as single object than you must do this-
NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myArray addObjectsFromArray:[paramsDictionary allValues]];
NSLog(#"%#",[paramsDictionary allValues]);
This is the NSDictionary I have:
locations: {
509f3a914d026b589ba3a090 = {
coordinates = {
latitude = "29.76429";
longitude = "-95.3837";
};
country = USA;
id = 509f3a914d026b589ba3a090;
name = Houston;
state = Texas;
};
509f3b3a4d026b589ba3a091 = {
coordinates = {
latitude = "3.138722";
longitude = "101.686849";
};
country = Malaysia;
id = 509f3b3a4d026b589ba3a091;
name = "Kuala Lumpur";
};
509f475b4d026b589ba3a093 = {
coordinates = {
latitude = "32.803468";
longitude = "-96.769879";
};
country = USA;
id = 509f475b4d026b589ba3a093;
name = Dallas;
state = Texas;
};
}
What I am wanting to do is to just get the countries and as you can tell I have two values for "USA". I just want to extrapolate USA and Malaysia. And not USA,Malaysia, USA.
I hope I am making sense
I think the simplest method would be:
[NSSet setWithArray:[[dictionary allValues] valueForKey:#"country"]];
So you:
get the array of all values in the top-level dictionary;
call valueForKey: on that array — which is defined to call valueForKey: on everything in the array in turn and then return an array of the answers, and valueForKey: on a dictionary is the same as objectForKey: if the key in question doesn't being with an '#';
create a set from the resulting array, hence resolving any repetitions.
You could add a call to allObjects on the resulting set if you wanted to end up with an array.
Say you have a dictionary called locations and one of the objects in your dictionary is a country. Also you say just extrapolate I'll assume you want to add it to some array or something. For this problem you could use a set to make sure you aren't entering the same country more then once.
NSMutableSet *set = [NSMutableSet set];
NSMutableArray *array = [NSMutableArray array];
NSString *country = [locations objectForKey:#"country"];
if ([set containsObject:country])
{
[array addObject:country]; // Extrapolating country from dictionary to array
[set addObject:country]; // Addind it to set to check later
}
I would do this way:
NSMutableArray *newArray = [NSMutableArray array];
NSMutableSet *currentCountries = [NSMutableSet set];
for(NSDictionary* dic in [[currentDict objectForKey:#"locations"] allValues])
{
if(![currentCountries containsObject:[dic objectForKey:#"country"])
{
[currentCountries addObject:[dic objectForKey:#"country"]]
[newArray addObject:dic];
}
}