How to Get Entire object from NSDictionary - ios

This is the my data.
NSDictionary *dictResponse = [[NSDictionary alloc]init];
//Here is dictResponse value is
(
{
"created_on" = "0000-00-00 00:00:00";
id = 627;
"modified_on" = "0000-00-00 00:00:00";
name = "";
"user_id" = 99;
},
{
"created_on" = "2016-05-06 14:43:45";
id = 625;
"modified_on" = "2016-05-06 14:43:45";
name = Ggg;
"user_id" = 99;
},
{
"created_on" = "2016-05-03 17:21:52";
id = 623;
"modified_on" = "2016-05-03 17:21:52";
name = Qwerty;
"user_id" = 99;
},
{
"created_on" = "2016-04-29 20:12:38";
id = 601;
"modified_on" = "2016-04-29 20:12:38";
name = Teat2;
"user_id" = 99;
},
{
"created_on" = "2016-04-29 20:12:27";
id = 600;
"modified_on" = "2016-04-29 20:12:27";
name = Test1;
"user_id" = 99;
},
{
"created_on" = "2016-05-09 13:04:00";
id = 626;
"modified_on" = "2016-05-09 13:04:00";
name = Testios;
"user_id" = 99;
})
Now I want to access complete one set object i.e.
{
"created_on" = "2016-04-29 20:12:27";
id = 600;
"modified_on" = "2016-04-29 20:12:27";
name = Test1;
"user_id" = 99;
}
from my dictResponse
so when I use
dictResponse[0] or dictResponse1 .. am getting error, so How can I retrieve entire one set from NSDictionary ?
please check below console log output.

You can do like that :
id arrResponse = dictResponse;
if ([arrResponse isKindOfClass:[NSArray class]] && arrResponse != nil && arrResponse != (id)[NSNull null])
{
NSArray *arrResults = arrResponse;
//if you want retrieve specific entries then here is the code for that
for (int i = 0 ; i<arrResults.count; i++) {
NSString *strName = [[arrResults objectAtIndex:i]valueForKey:#"name"];
NSString *strCreated_on = [[arrResults objectAtIndex:i]valueForKey:#"created_on"];
NSString *strModified_on = [[arrResults objectAtIndex:i]valueForKey:#"modified_on"];
NSInteger userID = [[arrResults objectAtIndex:i]valueForKey:#"user_id"];
}
}

You can't access objects in a dictionary using an index (like dictResponse[0]). Objects in a dictionary don't have indexes, they have keys. To get an object from a dictionary you use the objectForKey method:
NSObject* myObject = [dictResponse objectForKey:#"my_key"];

You have not given enough detail in your question, so the following is a guess:
so when I use dictResponse[0] or dictResponse[1] .. am getting error
You never say what error you are getting. I'm guessing you get a compile error and not an execution one?
You seem to know your code is wrong as in the comments you write:
Yes I know this is not valid dictionary value but it is possible to get something like that value in NSDictionary, so question is not wrong, yes my response is array of dictionary. Means from console log I can give dictResponse[0] and it prints first part as expected.
Exactly, you can break the type system and store an array reference into a variable which is typed as holding a dictionary reference, but doing so is not a good idea!
When the compiler sees dictResponse[0] it recognises it syntactically as an array indexing operation, so it looks for a method on dictResponse which does array indexing. All it knows about dictResponse, and remember this is happening at compiler time, is that you have stated it is an NSDictionary *, so it looks for an array indexing method supported by NSDictionary and does not find one, giving the error:
Expected method to read an array element not found on object of type 'NSDictionary *'
Try correctly typing you variable and see if your code works.
HTH

Related

Can't get value of NSSingleEntryDictionary

I have an NSDictionary, named "thisList", and I need to get the value of its key "list_collection".
Xcode indicates that the value is a "NSSingleEntryDictionary".
The value itself contains an array with yet another dictionary.
Please take a look at the screenshot:
Now, no matter what I try (objectforKey/valueforKey) or whatever type of object I initialize (NSArray/NsMutableArray/NSDictionary/NSMutableDictionary) I end up with a nil value.
Apparently, I miss some essential knowledge on how to handle this.
My question: how should I initialize an object with the value of the key "list_collection".
Here is a (partial) dump of the json:
Printing description of thisList:
{
archived = 0;
"chapter_part" = "";
"chapter_title" = "";
comment = "";
"cover_id" = "<null>";
"created_at" = "2017-01-06T12:59:04.000+01:00";
"date_created" = "06 January 2017";
deleted = 0;
id = 141384502;
isMyList = 1;
keywords = (
);
"list_collection" = {
lists = (
{
"speech_locale" = EN;
subject = engels;
words = (
{
word = attitude;
},
The to me most logical approach would be:
NSDictionary * myDic = [thisList objectForKey:#"list_collection"];
Note: I didn't explicitly initialize 'myDic' here.
To put things in context, here is my code:
NSString * hlists = [json objectForKey:#"lists"];
NSData* data = [hlists dataUsingEncoding:NSUTF8StringEncoding];
NSArray *wrtsLists = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParsingError];
Lists = [[NSMutableArray alloc]init];
for (NSDictionary *thisList in wrtsLists){
WordList* theList = [[WordList alloc]init];
theList.title = [thisList valueForKey:#"title"];
[Lists addObject:theList];
NSDictionary *myDic = thisList[#"list_collection"];
>>>>this is where I put a breakpoint. myDic is nil here
}
Thanks for your insights.
You can simply get "list_collection" array from "thisList" using by this code
NSDictionary *myDic = thisList[#"list_collection"];
In the end, I figured out, that it was an Xcode problem.
The Debug area just didn't correctly display the values of my objects.
I restarted Xcode, and things started to work as expected.
I lost several hours of my life on this. But I learned a lot, thanks to your good advises.
Try this hope it helps You
NSDictionary *myDic = [thelist valueForKey:"list_collection"];

NSDictionary - need to obtain value for key subelement

I have created an NSDictionary named "myData"
which contains the following JSON response:
{
listInfo = (
{
date = 1392157366000;
dateAsString = "02/11/2014 22:22:46";
id = 6;
address = 542160e0000c;
myLevel = 13;
},
{
date = 1392155568000;
dateAsString = "02/11/2014 21:52:48";
id = 5;
address = 542160e0000c;
myLevel = 13;
}
);
}
I need to retrieve each of the [dateAsString] key/value pairs.
I've tried: NSString *dateAsString=[[myData valueForKeyPath:#"dateAsString"][0] objectForKey:#"myData"]; without any luck.
Any suggestions are greatly appreciated.
I think this will work:
NSArray* dateStringArray = [listInfo valueForKeyPath:#"#unionOfObjects.dateAsString"]
I believe it will give you an array of strings. If you need to stuff that back in a dictionary, that should be fairly easy.
It's not clear what your "myData" looks like... so I used the listInfo array of dicts shown.

Extracting an NSDictionary from within another NSDictionary

My application has an NSDictionary containing many other NSDictionary inside it. If I print out this dictionary it reads as follows:
oxip = {
created = "2014-02-10 14:42:59";
lastMsgId = "";
requestTime = "1.6434";
response = {
code = 001;
debug = "";
message = success;
request = getHierarchyByMarketType;
text = "\n";
williamhill = {
class = {
id = 1;
maxRepDate = "2014-02-10";
maxRepTime = "07:31:48";
name = "UK Football";
text = "\n";
type = (
{
id = 2;
lastUpdateDate = "2013-12-26";
lastUpdateTime = "13:32:54";
market = (
{
betTillDate = "2014-02-15";
betTillTime = "15:00:00";
date = "2014-02-15";
id = 140780553;
lastUpdateDate = "2014-02-10";
lastUpdateTime = "14:09:13";
name = "Queen of the South v Dundee - Match Betting";
participant = (
{
handicap = "";
id = 496658381;
lastUpdateDate = "2014-02-10";
lastUpdateTime = "14:09:13";
name = Dundee;
odds = "11/8";
oddsDecimal = "2.38";
text = "\n\n\n\n\n\n";
},
{
handicap = "";
id = 496658380;
lastUpdateDate = "2014-02-10";
lastUpdateTime = "14:09:13";
name = Draw;
odds = "5/2";
oddsDecimal = "3.50";
text = "\n";
},
{
handicap = "";
id = 496658379;
lastUpdateDate = "2014-02-10";
lastUpdateTime = "14:09:13";
name = "Queen of the South";
odds = "11/8";
oddsDecimal = "2.38";
text = "\n";
}
);
text = "\n";
time = "15:00:00";
}
What is the best possible way for my application to reach the NSDictionary with the name of:
name = "Queen of the South v Dundee - Match Betting"
without the need of going through each individual dictionary and finding its object for key?
You can use valueForKeyPath for that. It accepts a path, separated by dots. Example:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://dl.dropboxusercontent.com/u/1365846/21680479.json"]]
options:0
error:nil];
NSLog(#"%#", [dict valueForKeyPath:#"response.williamhill.class.type.market.name"]);
This depends on the representation of dictionary. If the williamhill part is changing, then it does not work, of course.
There is no way to obtain a reference within a map data type (in this case, an NSDictionary) without traversing it. Think of the simplified version of this problem: You have a linked list with N elements and you wish to reach the N'th element. Because this is a linked list, you'll have to go through all other N-1 nodes in order to obtain the last reference.
An NSDictionary is a hash based data type in which keys and values are stored. In the case you describe, you have no reference to the nested object (an NSDictionary itself) so you must also traverse all of the dictionaries containing it.
Hope this helps point you in the right direction.

NSDictionary key comparison fails

I am dealing a very basic problem, I have two dictionary keys I need to compare but when I do it doesn't give me correct answer, somehow I am failing to create the logic.
So I have this in a plist array of dictionaries and json array comming from server
I want to compare them if event exist in plist do certain thing if not do another thing;
PROBLEM:
According to my logic if two events in plist are equal to other two events comming from server if logic should be printed per for each dictionary coming from server , so in this case 2 times total , but in my code it is printed 4 times. basically it is satisfying the condition every single time.
NSLOG:
evreka find the id
evreka find the id
evreka find the id
evreka find the id
SOURCE:
in a plist;
createList (
{
"end_date" = "2013-07-24";
ends = "13:07:00";
"event_id" = 173;
"event_name" = Static;
location = Asdad;
"root_folder" = "dadapof#gmail.com";
"start_date" = "2013-07-24";
starts = "13:07:00";
"user_id" = 13;
},
{
"end_date" = "2013-07-25";
ends = "13:08:00";
"event_id" = 174;
"event_name" = "Event Delete";
location = Asdsad;
"root_folder" = "dadapof#gmail.com";
"start_date" = "2013-07-25";
starts = "13:08:00";
"user_id" = 13;
}
)
This comming from server
responseobj (
{
"end_date" = "2013-07-24";
ends = "13:07:00";
"event_id" = 173;
"event_name" = Static;
location = Asdad;
"root_folder" = "dadapof#gmail.com";
"start_date" = "2013-07-24";
starts = "13:07:00";
"user_id" = 13;
},
{
"end_date" = "2013-07-25";
ends = "13:08:00";
"event_id" = 174;
"event_name" = "Event Delete";
location = Asdsad;
"root_folder" = "dadapof#gmail.com";
"start_date" = "2013-07-25";
starts = "13:08:00";
"user_id" = 13;
}
)
CODE:
Comparison code;
if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
createList= [NSMutableArray arrayWithContentsOfFile:dataPath];
NSLog(#"createList %#",createList);
NSLog(#"responseobj %#",responseObj);
//compare plist and response object
for (int i=0; i<[responseObj count]; i++) {
NSDictionary *dataDict = [responseObj objectAtIndex:i];
NSString *event_name =[dataDict objectForKey:#"event_name"];
//NSString *event_id =[dataDict objectForKey:#"event_id"];
BOOL eventExistInPlist=NO;
for (int j=0; j<[createList count]; j++) {
NSDictionary *createDict = [createList objectAtIndex:i];
//NSString *create_id =[createDict objectForKey:#"event_id"];
NSNumber *create_id =[createDict objectForKey:#"event_id"];
if ([[dataDict objectForKey:#"event_id"] isEqual:[createDict objectForKey:#"event_id"]]) {
// if (create_id==event_id) {
NSLog(#"evreka find the id");
What I have tried:
I have tried to compare them as strings(isEqualtoString), numbers(==) and isEqual: method , they have all failed.
What am I doing wrong?
In
NSDictionary *createDict = [createList objectAtIndex:i];
^----- HERE
you are using the wrong index, it should be j instead of i for the inner loop.
Martin R's answer is where your issue is. I would change your logic though to include Objective-C fast enumeration instead of the standard for ++ loop. I also separated out the second for loop into a BOOL method for easier reading
for (NSDictionary *dataDict in responseObj) {
NSString *event_name =[dataDict objectForKey:#"event_name"];
if ([self matchFoundForEventId:event_name]) {
NSLog(#"Match found");
}
}
-(BOOL)matchFoundForEventId:(NSString *)eventId {
for (NSDictionary *dataDict in createList) {
NSString *createEvent = [dataDict objectForKey:#"event_id"];
if ([eventId isEqualToString:createEvent]) {
return YES;
}
}
return NO;
}

How to Serialize a NSCFArray (possible JSON) to NSDictionary?

I'm really stuck right now while using BZForursquare to get nearby Venues into a UITableView.
BZFoursquare: https://github.com/baztokyo/foursquare-ios-api
I get my Requestresult inside the requestDidFinishLoading Delegate Method. In this Method the request Object contains several NSDictionaries and one Dictionary is in request.response. This response Dictionary contains one entry with key="venues" and as Value a JSON Object. When I put this value Object into a dictionary the type seems not to be a Dictionary but a NSCFArray:
#pragma mark BZFoursquareRequestDelegate
- (void)requestDidFinishLoading:(BZFoursquareRequest *)request {
self.meta = request.meta;
self.notifications = request.notifications;
self.response = [request.response objectForKey:#"venues"];
self.request = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"%#",[self.response objectForKey:#"name"]);
}
I assume this because the NSLog Line gives me the following error:
-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x1e5c90f0
Now I'm totaly confused and tried some failed attempts to get this JSON from whatever kind od Datatype it is into a NSDictionary. One attempt was to put the value Object into an NSString and use
[NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
to get it into a Dictionary but that also failed because it still remains a NSCFArray. Can someone please tell me how I get content of
[request.response objectForKey:#"venues"]
into a NSDictionary so that I can populate my UITabelview with this content?
EDIT:
Here is whats in the value part from the Dictionary request.response:
(
{
categories = (
{
icon = {
name = ".png";
prefix = "https://foursquare.com/img/categories/food/default_";
sizes = (
32,
44,
64,
88,
256
);
};
id = 4bf58dd8d48988d10b941735;
name = "Falafel Restaurant";
pluralName = "Falafel Restaurants";
primary = 1;
shortName = Falafel;
}
);
contact = {
};
hereNow = {
count = 0;
groups = (
);
};
id = 4df3489dfa76abc3d86c4585;
likes = {
count = 0;
groups = (
);
};
location = {
cc = DE;
city = "Vinn";
country = Germany;
distance = 92;
lat = "51.44985";
lng = "16.648693";
state = "Nordrhein-Westfalen";
};
name = "Yildiz D\U00f6ner";
specials = (
);
stats = {
checkinsCount = 3;
tipCount = 0;
usersCount = 2;
};
verified = 0;
}
And this seems to be from Type of NSCFArray. And how can I create from this another Dictionary so that I can access the JSON Values by key? Sorry if I'm really slow today...
You ask for "venues" which I assume is an array of such. So after deserializing the json, log the return object to see what you get. It's almost for sure an array of dictionaries.

Resources