How to IntersectSet of two NSDictionary or NSMutableDictionary with values? - ios

Want to merge two NSDictionary or NSMutableDictionary only with dict1 values. like [NSMutableDictionary addEntriesFromDictionary:] and intersectSet (from NSMutableSet).
Dict 1 = #{#”One”: #””, #”Two”: #”"}
Dict 2 = #{#”One”: #”1”, #”Two”: 2, #”Three”: #”3"}
My expect output after merge = #{#”One”: #”1”, #”Two”: #”2"}
UPDATE
I am already tried with [Dict1 addEntriesFromDictionary:Dict2] this one give answer #{#”One”: #”1”, #”Two”: 2, #”Three”: #”3"}
Also I am tried with NSMutableSet
NSMutableSet *keysInA = [NSMutableSet setWithArray:tempDict.allKeys];
NSSet *keysInB = [NSSet setWithArray:tempDict1.allKeys];
[keysInA intersectSet:keysInB];
NSLog(#"keys in A that are not in B: %#", keysInA);
This one give output One, Two, Three.
So [NSMutableSet setWithArray:] and [NSMutableDictionary addEntriesFromDictionary:] won't give what I expected.
If above code have anything work let clear me. Thanks.

NSDictionary *dict1 = #{#"One": #"", #"Two": #"6"};
NSDictionary *dict2 = #{#"One": #"1", #"Two": #"2", #"Three": #"3"};
NSDictionary * dict = [dict2 dictionaryWithValuesForKeys:[dict1 allKeys]];
NSLog(#"dict %#",dict);
// Log value
dict {
One = 1;
Two = 2;
}
Here what I expected.

try this...
//Assuming both dictionaries have same kind of keys
NSMutableDictionary *dict1 = #{#"One" : #"", #"Two": #"", #"Three" : #""}.mutableCopy;
NSDictionary *dict2 = #{#"One" : #"1", #"Two": #"2", #"Three" : #"3",#"Four":#"4"};
for (NSString *key in dict1.allKeys)
{
if (dict2[key])
{
dict1[key] = dict2[key];
}
}
NSLog(#"Updated dict %#",dict1);

Related

how to get nsDictionary element by using for-in

NSDictionary *myDict = #{#"one":#"1",#"two":#"2"};
for (NSDictionary* tmp in myDict) {
NSLog(#"%#",tmp);
}
resut:
my tmpis NSString
I want to get a dictionary with key= one , value = 1
for in for NSDictionary will iterate the keys.
for (NSString * key in myDict) {
NSLog(#"%#",key);
NSString * value = [myDict objectForKey:key];
}
If you want to get a dictionary. You have to create a dictionary from these values
for (NSString * key in myDict) {
NSLog(#"%#",key);
NSString * value = [myDict objectForKey:key];
NSDictionary * dict = #{key:value};
}
Or you should init like this:
NSArray *arrDict = #[{#{"one":#"1"},#{#"two":#"2"}];
for (NSDictionary* tmp in arrDict) {
NSLog(#"%#",tmp);
}
You can get all keys from your dic then add the key and value to your new dic like this:
NSDictionary *myDict = #{#"one":#"1",#"two":#"2"};
NSArray *keys = [myDict allKeys];
for (NSString *key in keys) {
NSDictionary *yourDic = #{key: [myDict valueForKey:key]};
NSLog(#"%#", yourDic);
}
You didn't create it that way. If you wanted to have a NSDictionary inside another NSDictionary you should write something like this :
NSDictionary *myDict = #{
#"firstDict" : #{
#"one":#"1"
},
#"secondDict": #{
#"two":#"2"
}
};
Above code will create a NSDictionary with two dictionaries at keys #firstDict and #secondDict.
Also, bear in mind, that because dictionaries are key-value pairs, using a for-in loop, actually loops through the keys in that dictionary. So your code is equivalent to:
for(NSString *key in dict.allKeys) { ... }
I got the solution
NSDictionary *myDict = #{#"one":#"1",#"two":#"2"};
NSMutableArray *arrayObject = [[NSMutableArray alloc]init];
NSMutableArray *arrayKey = [[NSMutableArray alloc]init];
NSMutableArray *arrayObjectKey = [[NSMutableArray alloc]init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
for (NSString *stringValue in myDict.allValues)
{
[arrayObject addObject:stringValue];
}
for (NSString *stringKey in myDict.allKeys)
{
[arrayKey addObject:stringKey];
}
for(int i = 0;i<[arrayKey count];i++)
{
dict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",[arrayKey objectAtIndex:i]],#"key",nil];
[dict setObject:[NSString stringWithFormat:#"%#",[arrayObject objectAtIndex:i]] forKey:#"value"];
[arrayObjectKey addObject:dict];
}
NSLog(#"The arrayObjectKey is - %#",arrayObjectKey);
The Output is
The arrayObjectKey is -
(
{
key = one;
value = 1;
},
{
key = two;
value = 2;
}
)
Create the dictionary:
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:#"1",#"One",#"2","Two",nil];
Get a value out using:(this example tmp will be 1)
NSString *tmp = [myDict objectForKey:#"One"];
Display the output in console:
NSLog(#"%#",tmp);
To display the whole NSDictionary
NSLog (#"contents of myDict: %#",myDict);
What you are doing is creating a dictionary with key-value pairs. I think what you want to do is have an array with dictionaries.
NSArray *myArray = #[#{#"one":#"1"}, #{#"two":#"2"}];
for (NSDictionary* tmp in myArray) {
NSLog(#"%#",tmp);
}
However I don't see a point in doing this. What you could do is:
NSDictionary *myDict = #{#"one":#"1",#"two":#"2"};
for (NSString* key in [myDict allKeys]) {
NSLog(#"%# = %#", key, myDict[key]);
}

NSDictionary format

Can anybody help me create an NSDictionary format of the following structure:
{
key1 = "value1";
key2 = "value2";
key3 = [
{
key01 = "value01";
key02 = "value02";
},
{
key01 = "value01";
key02 = "value02";
},
{
key01 = "value01";
key02 = "value02";
}
];
}
Try this code it might help you.
NSDictionary *dicationary = #{
#"key1":#"value1",
#"key2":#"value2",
#"key3":#[#{#"key01":#"value01",#"key02":#"value02"},
#{#"key01":#"value01",#"key02":#"value02"},
#{#"key01":#"value01",#"key02":#"value02"}]
};
There is API in obj-c to convert Json to nsdictionary .I guess you should try that :
First convert json to nsdata (assuming you above JSON is in string format)
2.Then you API to convert that to NSDictionary :
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Just to answer your question about converting that JSON data to NSDictionary, here it is:
(assuming you already got your JSON data)
// add the first 2 VALUES with it's KEYS
NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
[mainDict setValue:VALUE1 forKey:KEY1];
[mainDict setValue:VALUE2 forKey:KEY2];
// then for the last KEY, create a mutable array where you will store your sub dictionaries
NSMutableArray *ma = [NSMutableArray array];
NSMutableDictionary *subDict = [NSMutableDictionary dictionary];
[subDict setValue:SUB_VALUE1 forKey:SUB_KEY1];
[subDict setValue:SUB_VALUE1 forKey:SUB_KEY2];
[ma addObject:subDict];
// then add that array to your main dictionary
[mainDict setValue:ma forKey:KEY3];
// check the output
NSLog(#"mainDict : %#", mainDict);
// SAMPLE DATA - Test this if this is what you want
NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
[mainDict setValue:#"value1" forKey:#"key1"];
[mainDict setValue:#"value2" forKey:#"key2"];
NSMutableArray *ma = [NSMutableArray array];
NSMutableDictionary *subDict = [NSMutableDictionary dictionary];
[subDict setValue:#"subValue1" forKey:#"subKey1"];
[subDict setValue:#"subValue2" forKey:#"subKey2"];
[ma addObject:subDict];
[mainDict setValue:ma forKey:#"key3"];
NSLog(#"mainDict : %#", mainDict);
The following should work for you:
NSString *jsonString = #"{\"ID\":{\"Content\":268,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", jsonDict[#"ID"][#"Content"]);
Will return you:
268

xcode - set value of a nested object

I have a json from a service and I need to change the values of one obeject.
{
question = (
{
answer = (
{
Id = 1;
value = 1;
},
{
Id = 2;
value = 0;
}
);
},
.....
I use that code to directly access to the second "value" element and set it to "true"
NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSMutableDictionary *preguntasDict = [[NSMutableDictionary alloc] init];
preguntasDict =[[[dict valueForKey:#"question"]mutableCopy];
NSMutableDictionary *answer = [[NSMutableDictionary alloc] init];
respuestasDict =[[[[preguntasDict valueForKey:#"answer"]objectAtIndex:0]objectAtIndex:1] mutableCopy];
[respuestasDict setObject:[NSNumber numberWithBool:true] forKey:#"value"];
It works: "respuestasDict" changes but the whoole "dict" not.
My question is: how could rebuild the entire dictionary? or it is possible to access directly to the nested object and change it?
Note that perguntasDict and respuestasDict are mutable copies of your dictionaries, so basically you are editing copies of your dict. You need to access dict directly, like this:
NSArray *answers = dict[#"question"][#"answer"];
[answers firstObject][#"value"] = #(YES);
PS: Doing dict[#"question"] is the same thing as [dict objectForKey:#"question"]. Also, #(YES) is the same thing as [NSNumber numberWithBool:true]

How to replace the value of the key in NSMutableDictionary based on the another key value pair

I have one NSArray with NSMutableDictionaries .Example testArray =[dict1,dict2,dict3,dict4].
Each dictionary in the array is something like
dict1= {
country = "INDIA";
flag = "A";
Currency = "Rupees";
rate = 10;
}
The all values are changeable. Sometimes
dict1 = {
country = "USA";
flag = "SA";
Currency = "Dollar";
rate = 50;
}
I need to update the value of the key rate of all dictionaries in the testArray if country = "INDIA" and flag = "A" and Currency = "Rupees" and Do not need to change the value of the rate key all other dictionaries in side the testArray.
Just try the below.
for(NSMutableDictionary *dic in array)
{
if([[dic valueForKey:#"country"] isEqualToString:#"INDIA"] &&
[[dic valueForKey:#"flag"] isEqualToString:#"A"] &&
[[dic valueForKey:#"Currency"] isEqualToString:#"Rupees"])
{
[dic setValue:#"100" forKey:#"rate"];
}
}
Here is a complete example what you need
NSDictionary *dict1 = #{
#"country" : #"INDIA",
#"flag" : #"A",
#"Currency" : #"Rupees",
#"rate" : #10
};
NSDictionary *dict2 = #{
#"country" : #"USA",
#"flag" : #"SA",
#"Currency" : #"Dollar",
#"rate" : #50
};
NSArray *testArray = #[dict1, dict2];
NSMutableArray *testMutableArray = [testArray mutableCopy];
for (int i = 0; i < testMutableArray.count; i++) {
NSDictionary *country = testMutableArray[i];
if ([country[#"country"] isEqualToString:#"INDIA"] &&
[country[#"flag"] isEqualToString:#"A"] &&
[country[#"Currency"] isEqualToString:#"Rupees"])
{
NSMutableDictionary *countryMutable = [country mutableCopy];
countryMutable[#"rate"] = #100;
testMutableArray[i] = [countryMutable copy];
}
}
testArray = [testMutableArray copy];
Use NSMutableArray instead of NSArray.
then,
NSDictionary *dict = [testArray objectAtIndex:0];
dict[#"rate"] = #"11";
[testArray replaceObjectAtIndex:0 withObject:dict];
Hope this will help you.

How to create an NSDictionary with multiple keys?

I am not sure if what I am going to ask is actually an NSDictionary with multiple keys but ok.
What I want to do is create an NSDictionary with keys and values for my data and then convert it to JSON format. The JSON format would look exactly like this :
{
"eventData": {
"eventDate": "Jun 13, 2012 12:00:00 AM",
"eventLocation": {
"latitude": 43.93838383,
"longitude": -3.46
},
"text": "hjhj",
"imageData": "raw data",
"imageFormat": "JPEG",
"expirationTime": 1339538400000
},
"type": "ELDIARIOMONTANES",
"title": "accIDENTE"
}
I ve only used NSDictionaries like this :
NSArray *keys = [NSArray arrayWithObjects:#"eventDate", #"eventLocation", #"latitude" nil];
NSArray *objects = [NSArray arrayWithObjects:#"object1", #"object2", #"object3", nil];
dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
But the above format is not all about key - value.
So my question is how would the NSDictionary be , to fit the JSON format??
Thanks for reading my post , and sorry if any confusion.
You can have a NSDictionary inside another NSDictonary:
NSDictionary *eventLocation = [NSDictionary dictionaryWithObjectsAndKeys:#"43.93838383",#"latitude",#"-3.46",#"latitude", nil];
NSMutableDictionary *eventData = [NSDictionary dictionaryWithObjectsAndKeys:eventLocation,#"eventLocation", nil];
[eventData setObject:#"Jun 13, 2012 12:00:00 AM" forKey:#"eventDate"];
[eventData setObject:#"hjhj" forKey:#"text"];
.
.
.
NSMutableDictionary *finalDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:eventData,#"eventData", nil];
[finalDictionary setObject:#"ELDIARIOMONTANES" forKey:#"type"];
[finalDictionary setObject:#"accIDENTE" forKey:#"title"];
Now with Objective-C literals there is a much better, easier, and cleaner way of accomplishing this. Here is your exact dictionary with this new syntax:
NSDictionary *dictionary = #{
#"eventData": #{
#"eventDate": #"Jun 13, 2012 12:00:00 AM",
#"eventLocation": #{
#"latitude": #43.93838383,
#"longitude": #-3.46
},
#"text": #"hjhj",
#"imageData": #"raw data",
#"imageFormat": #"JPEG",
#"expirationTime": #1339538400000
},
#"type": #"ELDIARIOMONTANES",
#"title": #"accIDENTE"
};
// Prints: "43.93838383"
NSLog(#"%#", dictionary[#"eventData"][#"eventLocation"][#"latitude"]);
How to Create NSArray and with Access for object using NSDictionary ?
... Create NSArray
NSArray *studentkeys = [NSArray arrayWithObjects:#"studentName", #"studentBirthDate", #"studentCity", #"studentMobile" nil];
NSArray *objects = [NSArray arrayWithObjects:#"Pravin", #"27/08/1990", #"Bhavnagar",#"7878007531", nil];
...to Access to NSArray Object Using NSDictionary
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
Here is the structure:
Your root object is NSMutableDictionary
eventData - key for object NSMutableDictionary with keys and objects:
->key eventDate object NSString
->key eventLocation object NSMutableDictionary with keys and objects:
----> key latitude object NSNumber
----> key longitude object NSNumber
-> key text object NSString
-> key imageData object NSString later converted to NSData
-> key imageFormat object NSString
-> key expirationTime object NSNumber
type key for object NSString
title key for object NSString
if you want multiple categories , you can follow this format
NSDictionary *jsonObject = #{
#"data1":#[
#{
#"title":#"A"
#"subData" : #[
#{
#"title":#"aa"
}]
}
]
};

Resources