Can't get objectForKey from NSDictionary - ios

I am using this code: https://github.com/valentinlietz/MySQL-Connect to use MySQL queries in objective c. I use Count(*) to check if this row already exists.
I used this code to NSLog(); this dictionary. Code:
for(NSArray *row in response.responseDictionary){
NSLog(#"%#", row);
}
Result:
{
"" = "<null>";
"COUNT(*)" = 0;
}
But when I use [response.responseDictionary objectForKey:#"COUNT(*)"]; It's returning Unrecognized selector sent to instance.
Update:
Row:
Row: ( { "" = "<null>"; "COUNT()" = 0; } )
Dictionary:
Row: { "" = "<null>"; "COUNT()" = 0; }

I haven't worked with that project, but from https://github.com/valentinlietz/MySQL-Connect/blob/master/MySQL.m it looks to me that response.responseDictionary is the result
of converting the JSON response of the script https://github.com/valentinlietz/MySQL-Connect/blob/master/mysql.php to a Foundation object.
And the code
while($row = mysql_fetch_array($query))
{
for($i = 0; $i < 50; $i++) {
$arr2[$fields[$i]] = $row[$fields[$i]];
}
array_push($return_arr, $arr2);
}
echo json_encode($return_arr);
in that PHP script shows that the response is an array of dictionaries.
So if I am correct, the name and type of the responseDictionary property is badly chosen, because it is not an NSDictionary, but an NSArray where each object is an NSDictionary,
and the following should work:
NSArray *responseArray = (NSArray *)response.responseDictionary;
NSLog(#"count = %#", [[responseArray objectAtIndex:0] objectForKey:#"COUNT(*)"]);

Related

Save multiple values with same keys in NSMutableDictionary then store the dictionary in NSMutableArray

I know this question has been asked many times but not got the solution or i might not understood that's why posting the question.
for (int web=0; web<[web_arr count]; web++) {
AdditionalBookmark *web_book=[[AdditionalBookmark alloc]init];
UITextField *txtNam = (UITextField*)[self.view viewWithTag:1100+web];
NSString *txtName = txtNam.text;
UITextField *txtLin = (UITextField*)[self.view viewWithTag:1200+web];
NSString *txtLink = txtLin.text;
if ((txtName && txtName.length > 0)||(txtLink && txtLink.length > 0))
{
web_book.additionalBookmark_Name = txtName;
web_book.additionalBookmark_Link= txtLink;
web_book.contactDetails_Id=self.contactDetailsinfo.contactDetailsId;
web_book.additionalBookmark_Id=[[[web_arr objectAtIndex:web] valueForKey:#"WeblinkId"] intValue];
[dictWebLinks setObject:txtName forKey:#"WeblinkName"];
[dictWebLinks setObject:txtLink forKey:#"WeblinkUrl"];
[arrForWebLinks addObject:dictWebLinks];
}
[db updateIntoAdditionalBookmarkWithObject:web_book];
}
[dictUpdate setObject:arrForWebLinks forKey:#"Weblink"];
The problem am facing is this suppose there are two items in the array
Printing description of web_arr:
<__NSArrayM 0x170e4db60>(
{
WeblinkId = 9;
WeblinkName = Hdhd;
WeblinkUrl = "ie.comh";
},
{
WeblinkId = 10;
WeblinkName = Hd;
WeblinkUrl = "nd.com";
}
)
what i am getting is below:
Printing description of arrForWebLinks:
<__NSArrayM 0x170e4db30>(
{
WeblinkName = Hd;
WeblinkUrl = "nd.com";
},
{
WeblinkName = Hd;
WeblinkUrl = "nd.com";
}
)
dictionary is replacing the value for same key holding the latest value only, how can i mange to save the values in same format as in web_arr.
Any help is appreciable.
You are adding the same dictionary to the array over and over:
[dictWebLinks setObject:txtName forKey:#"WeblinkName"];
[dictWebLinks setObject:txtLink forKey:#"WeblinkUrl"];
[arrForWebLinks addObject:dictWebLinks];
You need to create a new one each time:
[arrForWebLinks addObject:#{
#"WeblinkName" : txtName,
#"WeblinkUrl" : txtLink
}];
(and remove dictWebLinks).

Parsing Json Output correctly

I am trying to correctly target the elements within the Json Output and I am getting closer but I presume there is a easy and obvious way I am missing.
My Json looks like this with a upper level event.
JSON SNIPPET UPDATED
chat = (
(
{
Key = senderId;
Value = {
Type = 0;
Value = "eu-west-1:91afbc3f-890a-4160-8903-688bf0e9efe8";
};
},
{
Key = chatId;
Value = {
Type = 0;
Value = "eu-west-1:be6457ce-bac1-412d-9307-e375e52e22ff";
};
},
{
Key = timestamp;
Value = {
Type = 1;
Value = 1430431197;
};
},
//Continued
I am targeting this level using
NSArray *chat = array[#"chat"];
for ( NSDictionary *theCourse in chat )
{
NSLog(#"---- %#", theCourse);
// I tried the following to target the values
//NSLog(#"chatId: %#", [theCourse valueForKey:#"Key"]);
//NSLog(#"timestamp: %#", theCourse[#"senderId"] );
}
}
I need to parse the value data for each key which if I was using an array would do like [theCourse valueForKey:#"Key"] but I think I may not be going deep enough?
As you would expect, [theCourse valueForKey:#"Key"] gives me the Key values but I need the associate values of those keys.
You can create an easier dictionary:
NSArray *chat = array[#"chat"][0];
NSMutableDictionary* newDict = [NSMutableDictionary dictionary];
for (NSDictionary* d in chat)
[newDict setValue:d[#"Value"][#"Value"] forKey:d[#"Key"]];
Now you can use the newDict.
NSLog(#"chatId: %#", [newDict valueForKey:#"chatId"]);

How to see if NSArray, created with valueForKey is empty

I got an array:
NSArray *itemsArray = [self.tournamentDetails.groups valueForKey:#"Items"];
Where self.tournamentDetails.groups is an NSArray, build with a JSON string from a webRequest.
Items is sometimes empty and sometimes it contains objects. So i need an if statement to check if its empty or not. I've tried some different things like:
if ([itemsArray count]!=0)
if (!itemsArray || !itemsArray.count)
Problem is that if my Items object from valueForKey is empty then the itemsArray still contains an object looking like this
<__NSArrayI 0x178abef0>(
<__NSArrayI 0x16618c30>(
)
)
When theres items inside my Items object it looks like this:
<__NSArrayI 0x18262b70>(
<__NSCFArray 0x181e3a40>(
{
BirthDate = 19601006T000000;
ClubName = "Silkeborg Ry Golfklub";
ClubShortName = "";
CompletedResultSum = {
Actual = {
Text = 36;
Value = 36;
};
ToPar = {
Text = "";
Value = 0;
};
};
}
)
)
Meaning that [itemsArray count] is always equal to 1 or more, and then it jumps into the if statement when it should not.
Anyone know how i can create an if statement where if itemsArray contains "Items:[]" it will be skipped and if itemsArray contains "Items:[lots of objects]" it will run?
EDIT: Solution is to check up on the first index like this if([[itemsArray objectAtIndex:0] count] != 0) then run code.
Try this:
if(itemsArray && itemsArray.count>0) //be sure that it has value){
for(NSArray *item in itemsArray){
if(item.count > 0){
// you have an NSDictionary. Will process it
}else{
//item.count == 0 : this is an empty NSArray.
}
}
}
more simpler
for (id obj in itemsArray)
{
if([obj isKindOfClass:[NSArray class]])
{
if(obj.count > 0)
{
//your if condition here
}
}
}

count dictionary with multiple keys in iOS

This is my JSON :
collections = {
items = (
{
nom = "automne-hiver-2012-2013";
},
{
nom = carbon;
},
{
nom = colors;
});
};
}
I access to my json like this:
int j=0;
NSString *collections=self.dictionaryMenu[#"collections"][#"items"][j][#"nom"];
I'm looking for count all the key "nom" who are in my JSON.
I try :
for (objectKey in self.dictionaryMenu.allKeys) {
count2 += [[self.dictionaryMenu objectForKey:objectKey] count];
NSLog(#"Anzahl: %d", count2);
}
NSString *counter = [NSString stringWithFormat:#"COUNT MENU (%d)", count2];
NSLog(#"%#",counter);
Unfortunately, it sends me 1 ( i think that's because there is only 1 "collections" in the JSON).
How can i count all the key "nom" ?
Try this:
NSArray *items = self.dictionaryMenu[#"collections"][#"items"];
NSUInteger count = 0;
for (NSDictionary *item in items) {
if (item[#"nom"]) {
count++;
}
}

iOS - How to parse Json array in xcode and save results are strings

Hi I am trying to parse a Json string as an NSArray and save certain results as strings to set permissions for different users in my app. My current code is:
NSError *jsonParsingError1 = nil;
accountData = [NSJSONSerialization JSONObjectWithData:jsonAccount
options:NSJSONReadingMutableContainers error:&jsonParsingError1];
accountData is an NSMutableArray created in the .h file.
jsonAccount is NSData created by converted an NSString
The NSLog out put for the array is;
{
account = "XXXX";
companyName = XXXXX;
id = XXXXX;
websites = (
{
account = "XXXXX";
accountId = XXXXX;
anonymiseIP = 0;
companyName = XXXXX;
XXXX = 0;
domains = (
"XXXXX"
);
features = {
advancedSegmentation = 1;
attentionHeatmaps = 1;
domains = 0;
dotHeatmaps = 1;
goalConversionTracking = 1;
interactionHeatmaps = 1;
leadInfo = 0;
scrollHeatmaps = 1;
timeHeatmaps = 1;
users = 0;
valueHeatmaps = 1;
visitorPlayback = 1;
visitorScoring = 1;
visitors = 1;
};
fixedElementSelector = "";
flagClicksReceived = 0;
flagDataReceived = 0;
flagGoalsReceived = 0;
flagInteractionsReceived = 0;
flagScrollsReceived = 0;
id = XXXXX;
interactionSelector = "";
name = "XXXX";
permissions = (
segments,
heatmaps,
visitors,
campaigns,
support,
globalSettings,
websiteSettings
);
setCookies = 1;
status = 1;
statusMessage = "";
statusString = OK;
trialling = 1;
}
);
},
When I try and create a sting from one of the results and display it in the log I get this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray:]: unrecognized selector sent to instance 0x6a950f0'
How can I save different keys as strings?
Looks like that your JSON is a Dictionary, not an Array.
Your JSON is not array you should parse it like NSDictionary
After parsing the JSON, you should test what kind of object it returned. E.g.:
if ([accountData isKindOfClass:[NSArray class]]) {
// handle like an array
} else if ([accountData isKindOfClass:[NSDictionary class]]) {
// handle like a dictionary
}
Your JSON is a dictionary with four keys: account, companyName, id, and websites.
The key "websites" will give you an array.
You can iterate through the "websites" array, and each element is a dictionary.
Each of the dictionaries in the "websites" array has lots of keys like account, accountId, anonymiseIP and so on. Some of these keys have values that are dictionaries or arrays.
In the NSLog statement, (a, b, c) would be an array, while { a = x; b = y; c = z; } would be a dictionary.
Your server response is a dictionary so change accountData to dictionary
Write NSLog for below and you will get information in it
[accountData objectForKey:#"account"];
[accountData objectForKey:#"companyName"];
[accountData objectForKey:#"id"];
[[accountData objectForKey:#"websites"] count];//array
[[[accountData objectForKey:#"websites"] objectAtIndex:0]objectForKey:#"account"];
[[[accountData objectForKey:#"websites"] objectAtIndex:0]objectForKey:#"domains"];
[[[[accountData objectForKey:#"websites"] objectAtIndex:0]objectForKey:#"domains"]count]; //array
[[[[accountData objectForKey:#"websites"] objectAtIndex:0]objectForKey:#"domains"]objectAtIndex:0];

Resources