how to get nsDictionary element by using for-in - ios

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

Related

Convert message received from PubNub to Dictionary object

I have the following object C code for receiving PubNub message.
- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
NSLog(#"Received message: %# on channel %# at %#", message.data.message,
message.data.subscribedChannel, message.data.timetoken);
}
The returned data is
Received message: (
{
key = userName;
value = Enoch;
},
{
key = photoID;
value = 3;
},
{
key = userID;
value = 1;
},
{
key = actionType;
value = chat;
},
{
key = message;
value = H;
}
) on channel chat at 14888810882049989
I would like to parse the message to a dictionary object for accessing the "value" by using the "key"
I am very new in objective C programming and don't know how to do.
Please help.
Loop through the message array and set the key value in dictionary.
NSArray *array = (NSArray*)message.data.message;
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
for (NSDictionary *item in array) {
[dic setObject:[item objectForKey:#"value"] forKey:[item objectForKey:#"key"]];
}
NSLog(#"%#", dic);
Or
NSArray *array = (NSArray*)message.data.message;
NSArray *values = [array valueForKey: #"value"];
NSArray *keys = [array valueForKey: #"key"];
NSDictionary *dic = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
NSLog(#"%#", dic);
You can use below method for parsing your data and convert it into dictionary
ChatterBoxMessage *chatterBoxMessage = [[ChatterBoxMessage alloc] initFromDictionary: message.data.message withTimeToken: message.data.timetoken];
[chatterBoxMessage asDictionary];
By This method you will get dictionary.
Above ChatterBoxMessage is a PubNub library class.
Also you can parse your data like below :
for (NSDictionary *objectData in message.data.message) {
NSLog(#"Value : %#",objectData[#"value"]);
NSLog(#"Key : %#",objectData[#"key"]);
}

how to search and replace in NSDictionary?

I have a JSON that I converted into NSDictionary and now I want to search and replace some values in it but I have no idea how to to this,
{
"CODE":200,
"APICODERESULT":"USER_INTERESTS",
"MESSAGE":"user interests fetched successfully",
"VALUE":{
"Books":[
{
"key":"7",
"value":"Fiction",
"selected":true
},
{
"key":"8",
"value":"Romantic",
"selected":true
}
],
"Music":[
{
"key":"11",
"value":"Classical",
"selected":false
},
{
"key":"12",
"value":"Jazz",
"selected":false
},
{
"key":"10",
"value":"Pop",
"selected":false
},
{
"key":"13",
"value":"Western",
"selected":false
}
]
}
}
here I have the value for key that I want to search in the dictionary and when I found that key with the value that I have I want to replace the value for selected in the same block.
For example:-
I have value 10 for key then I want to change the value for key selected to true
so the it will look like this
{
"CODE":200,
"APICODERESULT":"USER_INTERESTS",
"MESSAGE":"user interests fetched successfully",
"VALUE":{
"Books":[
{
"key":"7",
"value":"Fiction",
"selected":true
},
{
"key":"8",
"value":"Romantic",
"selected":true
}
],
"Music":[
{
"key":"11",
"value":"Classical",
"selected":false
},
{
"key":"12",
"value":"Jazz",
"selected":false
},
{
"key":"10",
"value":"Pop",
"selected":true
},
{
"key":"13",
"value":"Western",
"selected":false
}
]
}
}
Consider your input dictionary as mainDictionary and use following code:
NSMutableDictionary *valuesDic = [mainDictionary objectForKey:#"VALUES"];
NSArray *allPossibleKeysArray = [valuesDic allKeys];
for (int j=0; j<allPossibleKeysArray.count; j++) {
NSString *keyStr = [allPossibleKeysArray objectAtIndex:j];
NSArray *array = [valuesDic objectForKey:keyStr];
for (int i=0; i<array.count; i++) {
NSMutableDictionary *dictionary = [array objectAtIndex:i];
NSString *keyString = [NSString stringWithFormat:#"%#",[dictionary objectForKey:#"key"]];
if([keyString isEqualToString:keyvalue]){
[dictionary removeObjectForKey:#"selected"];
[dictionary setObject:[NSNumber numberWithBool:true] forKey:#"selected"];
}
}
}
Hope this helps!!
You should make such changes during parsing the JSON/moving it into model. The code below is a workaround:
NSDictionary *initialJson = //Your JSON here
NSArray *allSubKeys= [initialJson[#"Value"] allKeys];
// Your mutable output.
NSMutableDictionary *mutableJson = [initialJson mutableCopy]
for(NSString *key in allSubKeys) {//Music && Books
// Create another cointainer here
for(NSArray *arr in mutableJson[#"Value][key]) {
// Create another cointainer here
for(NSDictionary *dict in arr) {//key, value, selected
for (NSString *key2 in [dict allKeys]) {
if ([key2 isEqualToString:#"selected"] && [dict[#"value"] equals:#10]) {
// Save YES here
}
else {
// Just copy element
}
// Add object to parent container
}
// Add object to parent container
}
// Add object to parent container
}
// Add object to parent container
}
Here is full solution
NSString* str=#"{\"CODE\":200,\"APICODERESULT\":\"USER_INTERESTS\",\"MESSAGE\":\"user interests fetched successfully\",\"value\":{\"Books\":[{\"key\":\"7\",\"value\":\"Fiction\",\"selected\":true},{\"key\":\"8\",\"value\":\"Romantic\",\"selected\":true}],\"Music\":[{\"key\":\"11\",\"value\":\"Classical\",\"selected\":false},{\"key\":\"12\",\"value\":\"Jazz\",\"selected\":false},{\"key\":\"10\",\"value\":\"Pop\",\"selected\":false},{\"key\":\"13\",\"value\":\"Western\",\"selected\":false}]}}";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"dictionary before updating: %#", dictionary);
// copy old dict
NSMutableDictionary* newDict=[[[NSMutableDictionary alloc]init]autorelease];
[newDict addEntriesFromDictionary:dictionary];
// get the entry to be changed
NSMutableDictionary* valueDict=[[[NSMutableDictionary alloc]init]autorelease];
[valueDict addEntriesFromDictionary:newDict[#"value"]];
NSMutableArray* musicArray=[[[NSMutableArray alloc] init] autorelease];
[musicArray addObjectsFromArray:newDict[#"value"][#"Music"]];
// get the music array and change your property
NSMutableDictionary* musicDict2=[[[NSMutableDictionary alloc] init] autorelease];
[musicDict2 addEntriesFromDictionary:[musicArray objectAtIndex:2]];
[musicDict2 setValue:[NSNumber numberWithBool:YES] forKey:#"selected"];
[musicArray replaceObjectAtIndex:2 withObject:musicDict2];
// update the value dictionary
[valueDict setObject:musicArray forKey:#"Music"];
//update the new dictionary
[newDict setObject:valueDict forKey:#"value"];
NSLog(#"dictionary after updating: %#", newDict);

Put multiple arrays in Dictionary

I am parsing a CSV file multiple times with for loop, here I need to store these arrays one by one dictionary. There are very less questions in stack about adding NSArray to NSDictionary. I am parsing CSV with below code but I strucked at storing in NSDictionary, The program is terminating and showing warning at assigning string to dictionary
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSLog(#"Serail No %d %#",i,keysArray);
NSString *string = [NSString stringWithFormat:#"%d", i];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects: keysArray forKeys: string];
}
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSString *key = [NSString stringWithFormat:#"serial%d",i];
[dict setObject:keysArray forKey:key];
}
To get back data from dictionary,
NSArray *array = [dict valueForKey:#"serial24"];//to get array 24.
If I understand you correctly, you want to add the arrays to a dictionary, with the key being the string value of integer i ? What you need to do is allocate the dictionary outside your loop -
NSMutableDictionary *dict=[NSMutableDictionary new];
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSLog(#"Serial No %d %#",i,keysArray);
NSString *string = [NSString stringWithFormat:#"%d", i];
dict[string]=keysArray;
}
I am not sure why you would want to do this, because this is basically an array. You could simply do -
NSMutableArray *outputArray=[NSMutableArray new];
for (NSString *keysString in csvArray) {
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
[outputArray addObject:keysArray];
}

convert array format according to array character

I have array in this format
rows = [[NSArray alloc] initWithObjects:#"adam", #"alfred", #"ain", #"abdul", #"anastazja", #"angelica",
#"dennis" , #"deamon", #"destiny", #"dragon", #"dry", #"debug" #"drums",
#"Fredric", #"France", #"friends", #"family", #"fatish", #"funeral",
#"Mark", #"Madeline",
#"Nemesis", #"nemo", #"name",
#"Obama", #"Oprah", #"Omen", #"OMG OMG OMG", #"O-Zone", #"Ontario",
#"Zeus", #"Zebra", #"zed", nil];
But i need this in to following format
rows = #[#[#"adam", #"alfred", #"ain", #"abdul", #"anastazja", #"angelica"],
#[#"dennis" , #"deamon", #"destiny", #"dragon", #"dry", #"debug", #"drums"],
#[#"Fredric", #"France", #"friends", #"family", #"fatish", #"funeral"],
#[#"Mark", #"Madeline"],
#[#"Nemesis", #"nemo", #"name"],
#[#"Obama", #"Oprah", #"Omen", #"OMG OMG OMG", #"O-Zone", #"Ontario"],
#[#"Zeus", #"Zebra", #"zed"]];
Means that same starting character in to different dictionary
The easiest approach.
NSArray *rows = ...;
NSMutableDictionary *map = [NSMutableDictionary dictionary];
for (NSString *value in rows) {
NSString *firstLetter = [value substringToIndex:1];
if (!map[firstLetter]) {
map[firstLetter] = #[];
}
NSMutableArray *values = [map[firstLetter] mutableCopy];
[values addObject:value];
map[firstLetter] = values;
}
NSArray *finalRows = [map allValues];
Note that finalRows is not sorted.
If you want to sort your array by it's first letter, you can try this :
NSMutableArray *outputArray = [NSMutableArray new];
NSString *lastFirstLetter = nil;
for(NSString *value in rows) {
NSString *firstLetter = [[value substringToIndex:1] lowerString];
if(![lastFirstLetter isEqualToString:firstLetter]) {
lastFirstLetter = firstLetter;
[outputArray addObject:[NSMutableArray new]];
}
[[outputArray lastObject] addObject:value];
}
The idea is to iterate your input array and if the first letter of your word is different than the precedent, create a new array.

Get a value from nsdictionary

I want to give a key value from my NSDictionary and get the value associated to it.
I have this:
NSArray *plistContent = [NSArray arrayWithContentsOfURL:file];
NSLog(#"array::%#", plistContent);
dict = [plistContent objectAtIndex:indexPath.row];
cell.textLabel.text = [dict objectForKey:#"code"];
with plistContent :
(
{
code = world;
key = hello;
},
{
code = 456;
key = 123;
},
{
code = 1;
key = yes;
}
)
So how do I get "hello" by giving the dictionary "world"?
If I understand your question correctly, you want to locate the dictionary where "code" = "world" in order to get the value for "key".
If you want to keep the data structure as it is, then you will have to perform a sequential search, and one way to do that is simply:
NSString *keyValue = nil;
NSString *searchCode = #"world";
for (NSDictionary *dict in plistContents) {
if ([[dict objectForKey:#"code"] isEqualToString:searchCode]) {
keyValue = [dict objectForKey:#"key"]); // found it!
break;
}
}
However if you do alot of this searching then you are better off re-organizing the data structure so that it's a dictionary of dictionaries, keyed on the "code" value, converting it like this:
NSMutableDictionary *dictOfDicts = [[NSMutableDictionary alloc] init];
for (NSDictionary *dict in plistContents) {
[dictOfDicts setObject:dict
forKey:[dict objectForKey:#"code"]];
}
(note that code will break if one of the dictionaries doesn't contain the "code" entry).
And then look-up is as simple as:
NSDictionary *dict = [dictOfDicts objectForKey:#"world"]);
This will be "dead quick".
- (NSString*) findValueByCode:(NSString*) code inArray:(NSArray*) arr
{
for(NSDictonary* dict in arr)
{
if([[dict valueForKey:#"code"] isEqualToString:code])
{
return [dict valueForKey:#"key"]
}
}
return nil;
}

Resources