How to display data in Dictionary in custom UITableViewCell? - ios
I am using AFNetworking 3.0.
In View controller I have displayed multiple Speciality title in each cell. After tap on particular cell, I got response from server like following:
[{"dp":{"id":0,"qualification":"MD(Doctor)","reg_id":0,"specialization1":"Orthopaedics","specialization2":"Dermatologist","specialization3":"Neurology","url":"www.batras.com"},"ds":{"city":"agiripalle","consultation_fee":450,"contact_no":"1234567890","country":"India","id":18,"organization_name":"Batra","pin_code":"411052","reg_id":0,"state":"andhra pradesh","street_name":"jhbfahjf","wellness_flag":false},"reg":{"mobile_no":0,"name":"Batra","profile_id":0,"reg_id":157,"wellness_id":"251215782521"}},{"dp":{"id":0,"qualification":"MD(Doctor)","reg_id":0,"specialization1":"Orthopaedics","specialization2":"Dermatologist","specialization3":"Neurology","url":"www.batras.com"},"ds":{"city":"anur","consultation_fee":458,"contact_no":"1234567898","country":"India","id":19,"organization_name":"Danny","pin_code":"411052","reg_id":0,"state":"himachal pradesh","street_name":"afafwfw","wellness_flag":false},"reg":{"mobile_no":0,"name":"Batra","profile_id":0,"reg_id":157,"wellness_id":"251215782521"}},{"dp":{"id":0,"qualification":"MD(Doctor)","reg_id":0,"specialization1":"Orthopaedics","specialization2":"Dermatologist","specialization3":"Neurology","url":"www.batras.com"},"ds":{"city":"pabal","consultation_fee":500,"contact_no":"4512451252","country":"India","id":20,"organization_name":"Org Name","pin_code":"411052","reg_id":0,"state":"maharashtra","street_name":"afawafww","wellness_flag":false},"reg":{"mobile_no":0,"name":"Batra","profile_id":0,"reg_id":157,"wellness_id":"251215782521"}},{"dp":{"id":0,"qualification":"MD(Doctor)","reg_id":0,"specialization1":"Orthopaedics","specialization2":"Dermatologist","specialization3":"Neurology","specialization4":"Gynecologist","url":"danny.com"},"ds":{"city":"bumlitan","consultation_fee":504,"contact_no":"1234567898","country":"India","id":21,"organization_name":"Danny","pin_code":"411052","reg_id":0,"state":"andaman and nicobar islands","street_name":"East Street","wellness_flag":false},"reg":{"mobile_no":0,"name":"Danny","profile_id":0,"reg_id":167,"wellness_id":"311220165848"}},{"dp":{"id":0,"qualification":"MD(Doctor)","reg_id":0,"specialization1":"Orthopaedics","specialization2":"Dermatologist","specialization3":"Neurology","specialization4":"Gynecologist","url":"danny.com"},"ds":{"city":"amtala","consultation_fee":451,"contact_no":"1234567898","country":"India","id":22,"organization_name":"Danny","pin_code":"411052","reg_id":0,"state":"assam","street_name":"West","wellness_flag":false},"reg":{"mobile_no":0,"name":"Danny","profile_id":0,"reg_id":167,"wellness_id":"311220165848"}},{"dp":{"id":0,"qualification":"MD(Doctor)","reg_id":0,"specialization1":"Orthopaedics","specialization2":"Dermatologist","specialization3":"Neurology","specialization4":"Gynecologist","url":"danny.com"},"ds":{"city":"hala","consultation_fee":541,"contact_no":"1234567890","country":"India","id":23,"organization_name":"Danny Clinic","pin_code":"411123","reg_id":0,"state":"chandigarh","street_name":"Chandigarh","wellness_flag":false},"reg":{"mobile_no":0,"name":"Danny","profile_id":0,"reg_id":167,"wellness_id":"311220165848"}}]
After that I handle that response like following way:
NSLog(#"Response from specialization server : %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: responseObject options: kNilOptions error: nil];
if (ResponseArray.count >0)
{
_spclarr = [ResponseArray mutableCopy];
NSLog(#"special_array : %#",_spclarr);
_spclstr=[NSString stringWithFormat:#"%#",_spclarr];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:_spclstr forKey:#"spcl"];
[self performSegueWithIdentifier:#"doctorspcl" sender:self];
}
[self getdata:responseObject];
} failure:^(NSURLSessionTask *operation, NSError *error)
{
// If Error occure, then this is AlertController Appear
NSLog(#"Error: %#", error);
In next view:
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *s = [prefs stringForKey:#"spcl"];
NSLog(#"spcl: %#",s);
menuItems=[s componentsSeparatedByString:#","];
NSLog(#"menu: %#",menuItems);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [menuItems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Doctordetail";
DoctorDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
NSLog(#"content: %#",content);
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%ld",(long)indexPath.row);
NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
NSLog(#"Cell Clicked: %#",menuItems);
NSLog(#"content2: %#",content);
}
When I run app on simulator, it works. when I click on particular cell, the log prints data of that cell.
here is menuItems:
menu: (
"(\n {\n dp = {\n id = 0;\n qualification = \"MD(Doctor)\";\n \"reg_id\" = 0;\n specialization1 = Orthopaedics;\n specialization2 = Dermatologist;\n specialization3 = Neurology;\n url = \"www.batras.com\";\n };\n ds = {\n city = agiripalle;\n \"consultation_fee\" = 450;\n \"contact_no\" = 1234567890;\n country = India;\n id = 18;\n \"organization_name\" = Batra;\n \"pin_code\" = 411052;\n \"reg_id\" = 0;\n state = \"andhra pradesh\";\n \"street_name\" = jhbfahjf;\n \"wellness_flag\" = 0;\n };\n reg = {\n \"mobile_no\" = 0;\n name = Batra;\n \"profile_id\" = 0;\n \"reg_id\" = 157;\n \"wellness_id\" = 251215782521;\n };\n }",
"\n {\n dp = {\n id = 0;\n qualification = \"MD(Doctor)\";\n \"reg_id\" = 0;\n specialization1 = Orthopaedics;\n specialization2 = Dermatologist;\n specialization3 = Neurology;\n url = \"www.batras.com\";\n };\n ds = {\n city = anur;\n \"consultation_fee\" = 458;\n \"contact_no\" = 1234567898;\n country = India;\n id = 19;\n \"organization_name\" = Danny;\n \"pin_code\" = 411052;\n \"reg_id\" = 0;\n state = \"himachal pradesh\";\n \"street_name\" = afafwfw;\n \"wellness_flag\" = 0;\n };\n reg = {\n \"mobile_no\" = 0;\n name = Batra;\n \"profile_id\" = 0;\n \"reg_id\" = 157;\n \"wellness_id\" = 251215782521;\n };\n }",
"\n {\n dp = {\n id = 0;\n qualification = \"MD(Doctor)\";\n \"reg_id\" = 0;\n specialization1 = Orthopaedics;\n specialization2 = Dermatologist;\n specialization3 = Neurology;\n url = \"www.batras.com\";\n };\n ds = {\n city = pabal;\n \"consultation_fee\" = 500;\n \"contact_no\" = 4512451252;\n country = India;\n id = 20;\n \"organization_name\" = \"Org Name\";\n \"pin_code\" = 411052;\n \"reg_id\" = 0;\n state = maharashtra;\n \"street_name\" = afawafww;\n \"wellness_flag\" = 0;\n };\n reg = {\n \"mobile_no\" = 0;\n name = Batra;\n \"profile_id\" = 0;\n \"reg_id\" = 157;\n \"wellness_id\" = 251215782521;\n };\n }",
"\n {\n dp = {\n id = 0;\n qualification = \"MD(Doctor)\";\n \"reg_id\" = 0;\n specialization1 = Orthopaedics;\n specialization2 = Dermatologist;\n specialization3 = Neurology;\n specialization4 = Gynecologist;\n url = \"danny.com\";\n };\n ds = {\n city = bumlitan;\n \"consultation_fee\" = 504;\n \"contact_no\" = 1234567898;\n country = India;\n id = 21;\n \"organization_name\" = Danny;\n \"pin_code\" = 411052;\n \"reg_id\" = 0;\n state = \"andaman and nicobar islands\";\n \"street_name\" = \"East Street\";\n \"wellness_flag\" = 0;\n };\n reg = {\n \"mobile_no\" = 0;\n name = Danny;\n \"profile_id\" = 0;\n \"reg_id\" = 167;\n \"wellness_id\" = 311220165848;\n };\n }",
"\n {\n dp = {\n id = 0;\n qualification = \"MD(Doctor)\";\n \"reg_id\" = 0;\n specialization1 = Orthopaedics;\n specialization2 = Dermatologist;\n specialization3 = Neurology;\n specialization4 = Gynecologist;\n url = \"danny.com\";\n };\n ds = {\n city = amtala;\n \"consultation_fee\" = 451;\n \"contact_no\" = 1234567898;\n country = India;\n id = 22;\n \"organization_name\" = Danny;\n \"pin_code\" = 411052;\n \"reg_id\" = 0;\n state = assam;\n \"street_name\" = West;\n \"wellness_flag\" = 0;\n };\n reg = {\n \"mobile_no\" = 0;\n name = Danny;\n \"profile_id\" = 0;\n \"reg_id\" = 167;\n \"wellness_id\" = 311220165848;\n };\n }",
"\n {\n dp = {\n id = 0;\n qualification = \"MD(Doctor)\";\n \"reg_id\" = 0;\n specialization1 = Orthopaedics;\n specialization2 = Dermatologist;\n specialization3 = Neurology;\n specialization4 = Gynecologist;\n url = \"danny.com\";\n };\n ds = {\n city = hala;\n \"consultation_fee\" = 541;\n \"contact_no\" = 1234567890;\n country = India;\n id = 23;\n \"organization_name\" = \"Danny Clinic\";\n \"pin_code\" = 411123;\n \"reg_id\" = 0;\n state = chandigarh;\n \"street_name\" = Chandigarh;\n \"wellness_flag\" = 0;\n };\n reg = {\n \"mobile_no\" = 0;\n name = Danny;\n \"profile_id\" = 0;\n \"reg_id\" = 167;\n \"wellness_id\" = 311220165848;\n };\n }\n)"
)
and content:
content: (
{
dp = {
id = 0;
qualification = "MD(Doctor)";
"reg_id" = 0;
specialization1 = Orthopaedics;
specialization2 = Dermatologist;
specialization3 = Neurology;
url = "www.batras.com";
};
ds = {
city = agiripalle;
"consultation_fee" = 450;
"contact_no" = 1234567890;
country = India;
id = 18;
"organization_name" = Batra;
"pin_code" = 411052;
"reg_id" = 0;
state = "andhra pradesh";
"street_name" = jhbfahjf;
"wellness_flag" = 0;
};
reg = {
"mobile_no" = 0;
name = Batra;
"profile_id" = 0;
"reg_id" = 157;
"wellness_id" = 251215782521;
};
}
2016-12-21 13:52:48.184 Wellness_24x7[1223:55790] content:
{
dp = {
id = 0;
qualification = "MD(Doctor)";
"reg_id" = 0;
specialization1 = Orthopaedics;
specialization2 = Dermatologist;
specialization3 = Neurology;
url = "www.batras.com";
};
ds = {
city = anur;
"consultation_fee" = 458;
"contact_no" = 1234567898;
country = India;
id = 19;
"organization_name" = Danny;
"pin_code" = 411052;
"reg_id" = 0;
state = "himachal pradesh";
"street_name" = afafwfw;
"wellness_flag" = 0;
};
reg = {
"mobile_no" = 0;
name = Batra;
"profile_id" = 0;
"reg_id" = 157;
"wellness_id" = 251215782521;
};
}
2016-12-21 13:52:48.185 Wellness_24x7[1223:55790] content:
{
dp = {
id = 0;
qualification = "MD(Doctor)";
"reg_id" = 0;
specialization1 = Orthopaedics;
specialization2 = Dermatologist;
specialization3 = Neurology;
url = "www.batras.com";
};
ds = {
city = pabal;
"consultation_fee" = 500;
"contact_no" = 4512451252;
country = India;
id = 20;
"organization_name" = "Org Name";
"pin_code" = 411052;
"reg_id" = 0;
state = maharashtra;
"street_name" = afawafww;
"wellness_flag" = 0;
};
reg = {
"mobile_no" = 0;
name = Batra;
"profile_id" = 0;
"reg_id" = 157;
"wellness_id" = 251215782521;
};
}
2016-12-21 13:52:48.187 Wellness_24x7[1223:55790] content:
{
dp = {
id = 0;
qualification = "MD(Doctor)";
"reg_id" = 0;
specialization1 = Orthopaedics;
specialization2 = Dermatologist;
specialization3 = Neurology;
specialization4 = Gynecologist;
url = "danny.com";
};
ds = {
city = bumlitan;
"consultation_fee" = 504;
"contact_no" = 1234567898;
country = India;
id = 21;
"organization_name" = Danny;
"pin_code" = 411052;
"reg_id" = 0;
state = "andaman and nicobar islands";
"street_name" = "East Street";
"wellness_flag" = 0;
};
reg = {
"mobile_no" = 0;
name = Danny;
"profile_id" = 0;
"reg_id" = 167;
"wellness_id" = 311220165848;
};
}
2016-12-21 13:52:52.862 Wellness_24x7[1223:55790] content:
{
dp = {
id = 0;
qualification = "MD(Doctor)";
"reg_id" = 0;
specialization1 = Orthopaedics;
specialization2 = Dermatologist;
specialization3 = Neurology;
specialization4 = Gynecologist;
url = "danny.com";
};
ds = {
city = amtala;
"consultation_fee" = 451;
"contact_no" = 1234567898;
country = India;
id = 22;
"organization_name" = Danny;
"pin_code" = 411052;
"reg_id" = 0;
state = assam;
"street_name" = West;
"wellness_flag" = 0;
};
reg = {
"mobile_no" = 0;
name = Danny;
"profile_id" = 0;
"reg_id" = 167;
"wellness_id" = 311220165848;
};
}
2016-12-21 13:52:52.962 Wellness_24x7[1223:55790] content:
{
dp = {
id = 0;
qualification = "MD(Doctor)";
"reg_id" = 0;
specialization1 = Orthopaedics;
specialization2 = Dermatologist;
specialization3 = Neurology;
specialization4 = Gynecologist;
url = "danny.com";
};
ds = {
city = hala;
"consultation_fee" = 541;
"contact_no" = 1234567890;
country = India;
id = 23;
"organization_name" = "Danny Clinic";
"pin_code" = 411123;
"reg_id" = 0;
state = chandigarh;
"street_name" = Chandigarh;
"wellness_flag" = 0;
};
reg = {
"mobile_no" = 0;
name = Danny;
"profile_id" = 0;
"reg_id" = 167;
"wellness_id" = 311220165848;
};
}
)
2016-12-21 13:52:53.918 Wellness_24x7[1223:55790] content: (
{
dp = {
id = 0;
qualification = "MD(Doctor)";
"reg_id" = 0;
specialization1 = Orthopaedics;
specialization2 = Dermatologist;
specialization3 = Neurology;
url = "www.batras.com";
};
ds = {
city = agiripalle;
"consultation_fee" = 450;
"contact_no" = 1234567890;
country = India;
id = 18;
"organization_name" = Batra;
"pin_code" = 411052;
"reg_id" = 0;
state = "andhra pradesh";
"street_name" = jhbfahjf;
"wellness_flag" = 0;
};
reg = {
"mobile_no" = 0;
name = Batra;
"profile_id" = 0;
"reg_id" = 157;
"wellness_id" = 251215782521;
};
}
but my problem is, it doesn't display in UITableViewCell
I tried to display it like following way:
[cell.drname setText:[[content objectForKey:#"dp"]valueForKey:#"qualification"]];
as well as
[cell.drname setText:[NSString stringWithFormat:#"%#", [[content objectForKey:#"dp"]valueForKey:#"qualification"]]];
but it gives me error like:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x7a07c600'
I didn't get that, where I am wrong.
Please anyone can solve my issue. help will be appreciable.
you need to make following changes.
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:#"YourURL" parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSArray *ResponseArray = (NSArray *)responseObject;
if (ResponseArray.count >0)
{
_spclarr = [ResponseArray mutableCopy];
NSLog(#"special_array : %#",_spclarr);
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving Array to NSUserDefaults
[prefs setObject:_spclarr forKey:#"spcl"];
[prefs synchronize];
[self performSegueWithIdentifier:#"doctorspcl" sender:self];
}
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
In detail View Controller
-(void)viewDidLoad
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
//directly reading the array
menuItems = [prefs objectForKey:#"spcl"];
}
your cellForRowAtIndexPath should look like this
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSArray *menuItems = [prefs objectForKey:#"spcl"];
NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
[cell.textLabel setText:[[content objectForKey:#"dp"]valueForKey:#"qualification"]];
return cell;
}
When we get the response in array format then why are you storing it in NSUserDefaults as NSString ? To get rid of it you need to store an Array directly in NSUserDefaults and use that array directly.
The problem is you have a NSArray not NSDictionary. try this-
NSArray* arr = #[#{#"dp":#{#"id":#"0",#"qualification":#"MD(Doctor)"}},
#{#"ds":#{#"id":#"1",#"qualification":#"MD(Nurse)"}}];
NSDictionary *dpDict = [[arr objectAtIndex:0]objectForKey:#"dp"];
NSString *str = [dpDict valueForKey:#"qualification"];
here, you get the string. It doesn't crash.
In cellForRowAtIndexPath use
NSString *str = [[[menuItems objectAtIndex:indexPath.row]objectForKey:#"dp"]valueForKey:#"qualification"];
to get the string.
Try this:
NSDictionary *dpDict = [content objectForKey:#"dp"];
if (dpDict && [dpDict isKindOfClass:[NSDictionary class]] && [dpDict objectForKey:#"qualification"] != nil) {
[cell.drname setText:[dpDict objectForKey:#"qualification"]];
}
Related
How to sort Json value in NSDictionary Objective c?
I want to sort my nested Json array by location_name, My json is in nsdictionary Json array is apiResult:{ Description = "List of Location"; code = 200; locationList = ( { "location_id" = 481; "location_name" = "<null>"; "pre_fixied" = "$3.00"; "state_name" = Melbourne; status = 0; zone = "Zone 2"; "zone_id" = 30; }, { "location_id" = 461; "location_name" = "O'Halloran Hill"; "pre_fixied" = "$5.00"; "state_name" = Adelaide; status = 1; zone = "Zone 3"; "zone_id" = 31; }, { "location_id" = 460; "location_name" = "Sheidow Park"; "pre_fixied" = "$5.00"; "state_name" = Adelaide; status = 1; zone = "Zone 3"; "zone_id" = 31; }, { "location_id" = 459; "location_name" = "Hallett Cove"; "pre_fixied" = "$5.00"; "state_name" = Adelaide; status = 1; zone = "Zone 3"; "zone_id" = 31; }, { "location_id" = 458; "location_name" = "Eden Hills"; "pre_fixied" = "$5.00"; "state_name" = Adelaide; status = 1; zone = "Zone 3"; "zone_id" = 31; }, { "location_id" = 457; "location_name" = Glengowrie; "pre_fixied" = "$5.00"; "state_name" = Adelaide; status = 1; zone = "Zone 3"; "zone_id" = 31; } ); message = "List of Location"; status = Success; } its appearing by location id descending order i want this json by location name ascending order. I have sort location list array separately but i want whole json and locationlist by locationname order
try this locationDescriptor = [[NSSortDescriptor alloc] initWithKey:#"location_id" ascending:YES]; sortDescriptors = [NSArray arrayWithObject: locationDescriptor]; sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors]; Now change sortedArray into any other format as required.
First short Location Array. lets say your json result is NSDictionary *jsonResult; And filtered array is NSArray *filteredArray; Then NSMutableDictionary *filteredJson = [NSMutableDictionary new]; [filteredJson setObject:[jsonResult valueForKey:#"Description"] forKey:#"Description"]; [filteredJson setObject:[jsonResult valueForKey:#"code"] forKey:#"code"]; [filteredJson setObject:filteredArray forKey:#"locationList"]; [filteredJson setObject:[jsonResult valueForKey:#"message"] forKey:#"message"]; [filteredJson setObject:[jsonResult valueForKey:#"status"] forKey:#"status"];
Dictionary object can't convert into a JSON object objective-c
hello I have a NSMutableArray like this. <__NSArrayM 0x137e9f270>( { CanLoadMore = 0; IsFinalLevel = 1; NextLevelApprovers = ( ); OrgStructure = ( { CreatedBy = 1; CreatedDate = "2015-07-29T12:10:34.297"; Deleted = 0; DeletedBy = 0; DeletedDate = "1901-01-01T00:00:00"; EntityHeadCode = 17098; EntityHeadName = "<null>"; IsPermitted = 0; LegislativeCode = LKA; LevelId = 1; NodeId = 1; OrgEntity = Group; OrgLevelDescription = ""; OrgLevelName = "ABCD Holdings"; OrgStructureId = 1; ParentNodeId = 0; RefOrgLevelId = 1; Status = 1; UpdatedBy = 17113; UpdatedDate = "2016-04-07T08:53:13.727"; }, { CreatedBy = 17113; CreatedDate = "2016-04-06T12:17:19.75"; Deleted = 0; DeletedBy = 0; DeletedDate = "1901-01-01T00:00:00"; EntityHeadCode = 0; EntityHeadName = "<null>"; IsPermitted = 0; LegislativeCode = LKA; LevelId = 2; NodeId = 2; OrgEntity = Company; OrgLevelDescription = ""; OrgLevelName = "ABCD HCM"; OrgStructureId = 2; ParentNodeId = 1; RefOrgLevelId = 6; Status = 1; UpdatedBy = 17098; UpdatedDate = "2016-07-29T11:14:12.513"; } ); PreviousLevelCount = 0; RequestDetails = { AutoId = 20; LevelId = 1; ModuleId = 2; NoOfLevels = 1; ObjectId = 20; ObjectName = "Leave Request"; RequestForm = "{\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17227,\"LeaveYear\":2016,\"LeaveTypeCode\":1,\"LeaveReasonCode\":2,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-02T00:00:00\",\"EndDate\":\"2016-08-02T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"half\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"Test 1\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/02/2016\",\"EndDateString\":\"08/02/2016\",\"LeaveDayList\":[\"08/02/2016-FH,08/02/2016-SH\"],\"SystemLeaveTypeCode\":\"ANN\",\"LeaveTypeName\":\"ANNUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}"; RequestId = 20; RequestedDate = "2016-08-02T05:07:07.127"; WorkflowId = 2; }; RequesterDetails = { AdminRequesterName = ""; DisplayName = "<null>"; EmployeeCode = 17227; EmployeeNumber = MM0000019; EtfNo = ""; Gender = Female; ImagePath = "/profile/image/759006c5e4214f0"; Name = haniAAAA; }; } ) I want to convert this to JSON object. So I did like this. NSError *jsonError; NSData *objectData = [[[[dm.mutArraySelectedReq objectAtIndex:index] objectForKey:#"RequestDetails"] valueForKey:#"RequestForm"] dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError]; but my jsondictionary is always nil. What is the error with this RequestForm object. Please help me. Thanks UPDATE This is the string I want to convert into a json. {\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17227,\"LeaveYear\":2016,\"LeaveTypeCode\":1,\"LeaveReasonCode\":2,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-02T00:00:00\",\"EndDate\":\"2016-08-02T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"half\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"Test 1\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/02/2016\",\"EndDateString\":\"08/02/2016\",\"LeaveDayList\":[\"08/02/2016-FH,08/02/2016-SH\"],\"SystemLeaveTypeCode\":\"ANN\",\"LeaveTypeName\":\"ANNUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"} UPDATE - CORRECT STRING {\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17167,\"LeaveYear\":2016,\"LeaveTypeCode\":2,\"LeaveReasonCode\":0,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-01T00:00:00\",\"EndDate\":\"2016-08-01T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"full\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/01/2016\",\"EndDateString\":\"08/01/2016\",\"LeaveDayList\":[\"08/01/2016-FH,08/01/2016-SH\"],\"SystemLeaveTypeCode\":\"CAS\",\"LeaveTypeName\":\"CASUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":null,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"} WRONG STRING {\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17227,\"LeaveYear\":2016,\"LeaveTypeCode\":1,\"LeaveReasonCode\":2,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-02T00:00:00\",\"EndDate\":\"2016-08-02T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"half\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"Test 1\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/02/2016\",\"EndDateString\":\"08/02/2016\",\"LeaveDayList\":[\"08/02/2016-FH,08/02/2016-SH\"],\"SystemLeaveTypeCode\":\"ANN\",\"LeaveTypeName\":\"ANNUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}
Its working Fine NSString *str = #"{\"LeaveEntryCode\":0,\"RequestId\":0,\"EmployeeCode\":17167,\"LeaveYear\":2016,\"LeaveTypeCode\":2,\"LeaveReasonCode\":0,\"BaseType\":\"ess\",\"StartDate\":\"2016-08-01T00:00:00\",\"EndDate\":\"2016-08-01T00:00:00\",\"NoOfDays\":1.0,\"StartDateSession\":\"full\",\"EndDateSession\":\"full\",\"PreApproved\":false,\"ForDate\":\"1901-01-01T00:00:00\",\"Remarks\":\"\",\"CoveringPersonCode\":0,\"AttachedDocument\":null,\"RequestStatus\":\"P\",\"Deleted\":false,\"Status\":false,\"CreatedBy\":0,\"CreatedDate\":\"0001-01-01T00:00:00\",\"UpdatedBy\":0,\"UpdatedDate\":\"0001-01-01T00:00:00\",\"DeletedBy\":0,\"DeletedDate\":\"0001-01-01T00:00:00\",\"ModuleId\":2,\"ObjectId\":20,\"StartDateString\":\"08/01/2016\",\"EndDateString\":\"08/01/2016\",\"LeaveDayList\":[\"08/01/2016-FH,08/01/2016-SH\"],\"SystemLeaveTypeCode\":\"CAS\",\"LeaveTypeName\":\"CASUAL\",\"Employee\":null,\"LieuDayList\":null,\"BaseLeaveType\":\"ANN\",\"CoveringPersonName\":null,\"LeaveReasonName\":\"Leave TypeCasual - Leave - Leave Reason\",\"DocumentSource\":\"LEAVE\"}" ; NSError *jsonError; NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError]; **OutPut** Printing description of json: { AttachedDocument = "<null>"; BaseLeaveType = ANN; BaseType = ess; CoveringPersonCode = 0; CoveringPersonName = "<null>"; CreatedBy = 0; CreatedDate = "0001-01-01T00:00:00"; Deleted = 0; DeletedBy = 0; DeletedDate = "0001-01-01T00:00:00"; DocumentSource = LEAVE; Employee = "<null>"; EmployeeCode = 17167; EndDate = "2016-08-01T00:00:00"; EndDateSession = full; EndDateString = "08/01/2016"; ForDate = "1901-01-01T00:00:00"; LeaveDayList = ( "08/01/2016-FH,08/01/2016-SH" ); LeaveEntryCode = 0; LeaveReasonCode = 0; LeaveReasonName = "Leave TypeCasual - Leave - Leave Reason"; LeaveTypeCode = 2; LeaveTypeName = CASUAL; LeaveYear = 2016; LieuDayList = "<null>"; ModuleId = 2; NoOfDays = 1; ObjectId = 20; PreApproved = 0; Remarks = ""; RequestId = 0; RequestStatus = P; StartDate = "2016-08-01T00:00:00"; StartDateSession = full; StartDateString = "08/01/2016"; Status = 0; SystemLeaveTypeCode = CAS; UpdatedBy = 0; UpdatedDate = "0001-01-01T00:00:00"; }
Try NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:0 error:&jsonError]; Don't give any options.
Retrieve a data from json ios
This is the content of dictionary *data Data = { Specialities = ( { ApprovalStatus = Unapproved; CurrencyCode = "<null>"; Packages = "<null>"; Photos = "<null>"; ServiceDescription = 356563; Speciality = 22; SpecialityName = "Wedding Photographer"; UserFRPs = "<null>"; Videos = ( { VideoId = TWhSjpsGvPQ; VideoLink = "http://www.youtube.com/watch?v=TWhSjpsGvPQ"; VideoType = YouTube; }, { VideoId = N2CJrhHEydA; VideoLink = "http://www.youtube.com/watch?v=N2CJrhHEydA"; VideoType = YouTube; }, { VideoId = Lq6faQVYcwY; VideoLink = "http://www.youtube.com/watch?v=Lq6faQVYcwY"; VideoType = YouTube; }, { VideoId = v8WjMiodcKo; VideoLink = "http://www.youtube.com/watch?v=v8WjMiodcKo"; VideoType = YouTube; } ); }, { ApprovalStatus = Unapproved; CurrencyCode = "<null>"; Packages = "<null>"; Photos = "<null>"; ServiceDescription = 52454353; Speciality = 37; SpecialityName = "Hair and Makeup Stylist"; UserFRPs = "<null>"; Videos = "<null>"; }, { ApprovalStatus = Unapproved; CurrencyCode = "<null>"; Packages = "<null>"; Photos = "<null>"; ServiceDescription = 21212; Speciality = 55; SpecialityName = Transport; UserFRPs = "<null>"; Videos = "<null>"; } ); }; } This is the response i am getting from json, what logic should i write to retrieve "VideoId" linked to a specific "Speciality" (for ex- Speciality = 22) if i write following code, i am getting all #"VideoId" [[[[responseDictionary valueForKey:#"Data"]valueForKey:#"Specialities"]valueForKey:#"Videos"]valueForKey:#"VideoId"]
The parsing way will be something like: NSDictionary *dataDict = [responseDictionary valueForKey:#"Data"]; NSMutableArray *specialityArray = [dataDict valueForKey:#"Specialities"]; NSDictionary *objectDict = [specialityArray objectAtIndex:your index (0/1/2)]; int *speciality = [[objectDict ValueForKey:#"Speciality"] intValue]; if(speciality = 22) { NSMutableArray *videoArray = [objectDict valueForKey:#"Videos"]; NSDictionary *videoObject = [videoArray objectAtIndex:your index (0/1/2)]; NSString *videoID = [videoObject valueForKey:#"VideoId"]; } Parse the rest accordingly as per your need.
Use this code, NSArray *wholeArray = [[responseDictionary objectForKey:#"Data"] valueForKey:#"Specialities"]; NSArray *subArray = [[wholeArray objectAtIndex:0] valueForKey:#"Videos"]; subArray is get all the videos values, then you get single value use this code, NSString *videoID = [[subArray objectAtIndex:i] valueForKey:#"VideoId"]; or you will get all videoID in single variable use this below code, NSMutableArray *tempArray = [[NSMutableArray alloc] init]; for (int i = 0; i < subArray.count; i++) { [tempArray addObject:[[subArray objectAtIndex:i] valueForKey:#"VideoId"]]; } finally tempArray get All the VideoID values, anywhere you use, NSString *videoID = [tempArray objectAtIndex:0/1/2]; hope its helpful
Issues parsing a dictionary
Below is a dictionary I have created by retrieving the my twitter statuses for an App Only twitter feed. I have parsed and returned the value of "text" successfully, and displayed it in a table view cell as follows: static NSString *cellID = #"FeedCell3" ; FeedCell3 *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; if (cell == nil) { cell = [[FeedCell3 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID]; } NSInteger idx = indexPath.row; NSDictionary *t = self.twitterDataSource[idx]; cell.updateLabel.text = t[#"text"]; return cell; However, when I try to return other values for keys such as "profile_image_url" and "screen_name" using the method below, an (null) is returned, even though there is a value in the dictionary. What am I doing wrong? cell.nameLabel.text = t[#"screen_name"]; NSURL *profileImageURL = t[#"profile_image_url"]; NSLog(#"%#", profileImageURL); Dictionary Data: contributors = "<null>"; coordinates = "<null>"; "created_at" = "Thu May 01 20:15:32 +0000 2014"; entities = { hashtags = ( ); symbols = ( ); urls = ( ); "user_mentions" = ( ); }; "favorite_count" = 0; favorited = 0; geo = "<null>"; id = 461962182734217473; "id_str" = 46398745473; "in_reply_to_screen_name" = "<null>"; "in_reply_to_status_id" = "<null>"; "in_reply_to_status_id_str" = "<null>"; "in_reply_to_user_id" = "<null>"; "in_reply_to_user_id_str" = "<null>"; lang = fr; place = "<null>"; "retweet_count" = 0; retweeted = 0; source = web; text = "Test Tweet"; truncated = 0; user = { "contributors_enabled" = 0; "created_at" = "Sun Mar 23 21:18:10 +0000 2014"; "default_profile" = 1; "default_profile_image" = 1; description = ""; entities = { description = { urls = ( ); }; }; "favourites_count" = 0; "follow_request_sent" = "<null>"; "followers_count" = 1; following = "<null>"; "friends_count" = 6; "geo_enabled" = 0; id = 24072342084; "id_str" = 242344084; "is_translation_enabled" = 0; "is_translator" = 0; lang = en; "listed_count" = 0; location = ""; name = "My Name"; notifications = "<null>"; "profile_background_color" = C0DEED; "profile_background_image_url" = "http://abs.twimg.com/images/themes/theme1/bg.png"; "profile_background_image_url_https" = "https://abs.twimg.com/images/themes/theme1/bg.png"; "profile_background_tile" = 0; "profile_image_url" = "http://abs.twimg.com/sticky/default_profile_images/default_profile_1_normal.png"; "profile_image_url_https" = "https://abs.twimg.com/sticky/default_profile_images/default_profile_1_normal.png"; "profile_link_color" = 0084B4; "profile_sidebar_border_color" = C0DEED; "profile_sidebar_fill_color" = DDEEF6; "profile_text_color" = 333333; "profile_use_background_image" = 1; protected = 0; "screen_name" = ScreenName; "statuses_count" = 2; "time_zone" = "<null>"; url = "<null>"; "utc_offset" = "<null>"; verified = 0; };
Those latter two keys you're going for are in the user dictionary, so try t[#"user"][#"screen_name"]; t[#"user"][#"profile_image_url"]; The second issue will appear when you solve the first. The url is a string. To get a proper NSURL you'll need to use an NSURL class method. NSURL *aURL = [NSURL URLWithString:t[#"user"][#"profile_image_url"]];
Trying to get the sum of a property in an array
I have an NSArray of objects and the data looks like this. I am currently trying to sum up the value of hours in the timeSheets property of the task given. I currently have a double for loop that does the job for the iPhone however it runs into a performance issue with lag on a UITableView on the iPad version. The code for the double for loop is at the bottom. I'm trying to use a mixture of NSExpressions and NSPredicates however, I cant seem to get these to add correctly. <Tasks: 0xc563950> (entity: Tasks; id: 0xc561940 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Tasks/p8> ; data: { assigneeID = 20; budgetedHours = 5; chargeNumber = 0; completedProgress = 0; createdBy = "Tyler Baetz"; dateCreated = "2013-09-06 19:18:40 +0000"; dateModified = "2013-09-11 04:53:32 +0000"; descriptions = nil; dueDate = "2013-09-11 07:00:00 +0000"; modifiedBy = "Jose Alvarez"; name = Denver; ownerID = 120; parentID = 1914; project = "0xc566070 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Projects/p2>"; projectID = 500910; taskID = 1916; taskPriority = nil; taskPriorityID = 1; taskStatus = nil; taskStatusID = 3; taskType = nil; taskTypeID = 4; tasks = "<relationship fault: 0xb4e9db0 'tasks'>"; timeSheets = ( "0xc553780 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p12>", "0xc5537a0 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p14>", "0xc5537b0 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p15>" ); }) with objects {( <TimeSheets: 0xc555420> (entity: TimeSheets; id: 0xc553780 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p12> ; data: { approvedBy = nil; comments = nil; dateApproved = nil; dateEntered = "2013-09-06 20:31:31 +0000"; employee = nil; employeeID = 20; enteredBy = 20; hours = 173; reportPeriod = nil; reportPeriodID = 4; task = "0xc561940 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Tasks/p8>"; taskID = 1916; timeSheetDate = "2013-09-01 07:00:00 +0000"; timeSheetID = 1934; timeStatus = nil; timeStatusID = 1; timeType = nil; timeTypeID = 35; }), <TimeSheets: 0xc555730> (entity: TimeSheets; id: 0xc5537a0 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p14> ; data: { approvedBy = nil; comments = "Friday :45"; dateApproved = nil; dateEntered = "2013-09-06 20:31:31 +0000"; employee = nil; employeeID = 20; enteredBy = 20; hours = 45; reportPeriod = nil; reportPeriodID = 4; task = "0xc561940 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Tasks/p8>"; taskID = 1916; timeSheetDate = "2013-09-06 07:00:00 +0000"; timeSheetID = 1937; timeStatus = nil; timeStatusID = 1; timeType = nil; timeTypeID = 35; }), <TimeSheets: 0xc5557a0> (entity: TimeSheets; id: 0xc5537b0 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p15> ; data: { approvedBy = nil; comments = "Hello Man"; dateApproved = nil; dateEntered = "2013-09-11 13:20:19 +0000"; employee = nil; employeeID = 20; enteredBy = 50; hours = 300; reportPeriod = nil; reportPeriodID = 4; task = "0xc561940 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Tasks/p8>"; taskID = 1916; timeSheetDate = "2013-09-05 07:00:00 +0000"; timeSheetID = 2357; timeStatus = nil; timeStatusID = 1; timeType = nil; timeTypeID = 35; }) )}, Relationship 'timeSheets' on managed object (0xc5639f0) <Tasks: 0xc5639f0> (entity: Tasks; id: 0xc561950 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Tasks/p9> ; data: { assigneeID = 20; budgetedHours = 3; chargeNumber = 0; completedProgress = 0; createdBy = "Tyler Baetz"; dateCreated = "2013-09-06 19:17:01 +0000"; dateModified = "2013-09-12 18:34:55 +0000"; descriptions = nil; dueDate = "2013-09-09 07:00:00 +0000"; modifiedBy = "Jose Alvarez"; name = "Jose's Task"; ownerID = 120; parentID = 1913; project = "0xc566070 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Projects/p2>"; projectID = 500910; taskID = 1915; taskPriority = nil; taskPriorityID = 4; taskStatus = nil; taskStatusID = 3; taskType = nil; taskTypeID = 4; tasks = "<relationship fault: 0xb4ee0d0 'tasks'>"; timeSheets = ( "0xc5537c0 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p16>", "0xc553810 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p21>", "0xc553800 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p20>", "0xc553790 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p13>", "0xc5537d0 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p17>" ); }) with objects {( <TimeSheets: 0xc5557f0> (entity: TimeSheets; id: 0xc5537c0 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p16> ; data: { approvedBy = nil; comments = nil; dateApproved = nil; dateEntered = "2013-09-11 17:05:11 +0000"; employee = "0xb4b8660 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Employees/p23>"; employeeID = 20; enteredBy = 20; hours = 205; reportPeriod = nil; reportPeriodID = 5; task = "0xc561950 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Tasks/p9>"; taskID = 1915; timeSheetDate = "2013-09-11 17:05:18 +0000"; timeSheetID = 2633; timeStatus = nil; timeStatusID = 1; timeType = nil; timeTypeID = 35; }), <TimeSheets: 0xc5559b0> (entity: TimeSheets; id: 0xc553810 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p21> ; data: { approvedBy = nil; comments = Rarer; dateApproved = nil; dateEntered = "2013-09-17 22:05:11 +0000"; employee = "0xb4b8660 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Employees/p23>"; employeeID = 20; enteredBy = 20; hours = 0; reportPeriod = nil; reportPeriodID = 6; task = "0xc561950 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Tasks/p9>"; taskID = 1915; timeSheetDate = "2013-09-19 07:00:00 +0000"; timeSheetID = 3297; timeStatus = nil; timeStatusID = 1; timeType = nil; timeTypeID = 35; }), <TimeSheets: 0xc555950> (entity: TimeSheets; id: 0xc553800 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p20> ; data: { approvedBy = nil; comments = Cbfb; dateApproved = nil; dateEntered = "2013-09-17 22:33:05 +0000"; employee = "0xb4b8660 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Employees/p23>"; employeeID = 20; enteredBy = 20; hours = 0; reportPeriod = nil; reportPeriodID = 6; task = "0xc561950 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Tasks/p9>"; taskID = 1915; timeSheetDate = "2013-09-16 07:00:00 +0000"; timeSheetID = 3298; timeStatus = nil; timeStatusID = 1; timeType = nil; timeTypeID = 35; }), <TimeSheets: 0xc5556c0> (entity: TimeSheets; id: 0xc553790 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p13> ; data: { approvedBy = nil; comments = nil; dateApproved = nil; dateEntered = "2013-09-12 18:34:55 +0000"; employee = "0xb4b8660 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Employees/p23>"; employeeID = 20; enteredBy = 20; hours = 284; reportPeriod = nil; reportPeriodID = 5; task = "0xc561950 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Tasks/p9>"; taskID = 1915; timeSheetDate = "2013-09-12 18:21:59 +0000"; timeSheetID = 2827; timeStatus = nil; timeStatusID = 1; timeType = nil; timeTypeID = 35; }), <TimeSheets: 0xc555850> (entity: TimeSheets; id: 0xc5537d0 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/TimeSheets/p17> ; data: { approvedBy = nil; comments = Asdad; dateApproved = nil; dateEntered = "2013-09-17 22:03:32 +0000"; employee = "0xb4b8660 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Employees/p23>"; employeeID = 20; enteredBy = 20; hours = 0; reportPeriod = nil; reportPeriodID = 6; task = "0xc561950 <x-coredata://36042CA3-F392-46FB-AF23-F0C396CE0989/Tasks/p9>"; taskID = 1915; timeSheetDate = "2013-09-15 07:00:00 +0000"; timeSheetID = 3296; timeStatus = nil; timeStatusID = 1; timeType = nil; timeTypeID = 35; }) )} ) Code For Double For Loop: - (NSNumber *) getSumOfChargedHoursForAnArrayOfTasks: (NSArray *) tasksArray { NSArray *timeSheets = [tasksArray valueForKeyPath:#"timeSheets"]; NSNumber *chargedHours = [NSNumber numberWithInt:0]; for(int i = 0; i < [timeSheets count]; ++i) { NSArray *innerTimeSheet = [timeSheets objectAtIndex:i]; for(int j = 0; j < [innerTimeSheet count]; ++j) { NSNumber *innerNumber = [innerTimeSheet valueForKeyPath:#"#sum.hours"]; chargedHours = [NSNumber numberWithFloat:[chargedHours intValue] + [innerNumber intValue]]; } } return chargedHours; }
If you are trying to sum the hours in all the time sheets in an array of tasks, then you should consider using valueForKeyPath: in the following way: [tasks valueForKeyPath:#"#sum.timeSheets.#sum.hours"] It appears that now, you are multiplying the sum of hours in the timeSheets for each task by the number of time sheets for each task.