Trying to get the sum of a property in an array - ios

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.

Related

Remove " " from key string in a NSMutableDictionary

Here's my dictionary:
Birthdate = "01-01-0001";
CareerField = 3;
Gender = 2;
"Interests[0].UserProfileId" = 19594;
"Interests[0].UserSurveyId" = 1;
SocialStatus = 2;
Studies = 3;
But I want the Interests key to be without "".Like that:
Birthdate = "01-01-0001";
CareerField = 3;
Gender = 2;
Interests[0].UserProfileId = 19594;
Interests[0].UserSurveyId = 1;
SocialStatus = 2;
Studies = 3;
UPDATE:
Interests i must send them like array.
[dict setObject:self.birthdayDate forKey:#"Birthdate"]
[dict setObject:#(self.occupationPickerRow + 1) forKey:#"CareerField"];
for (int i = 0; i < [interestsArray count]; i++) {
NSString *stringSurveyId = [NSString stringWithFormat:#"%#%d%#", #"Interests[", indexCount, #"].UserSurveyId"];
NSString *stringUserProfileId = [NSString stringWithFormat:#"%#%d%#", #"Interests[", indexCount, #"].UserProfileId"];
[dict setObject:[interestsArray objectAtIndex:i] forKey:stringSurveyId];
[dict setObject:#([[[MZEngine sharedInstance] currentUserModel] userId]) forKey:stringUserProfileId];
indexCount++;
}

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.

Sort Descriptor not working in ios

i used the Sort Descriptor to Sort the NSMutableArray By one & multiple Values,First i tried by to sort By Price,it sort in some other Order here is my code help me,
My
i create the Dictionary by below code and added to the NSMutableArray
for(int i=0;i<[priceArray count];i++)
{
cellDict=[[NSMutableDictionary alloc]init];
[cellDict setObject:nameArray[i] forKey:#"Name"];
[cellDict setObject:splPriceArray[i] forKey:#"Percentage"];
[cellDict setObject:priceArray[i] forKey:#"Price"];
[resultArray addObject:cellDict];
}
// To Sort in Ascending Order
NSSortDescriptor *sort =[[NSSortDescriptor alloc] initWithKey:#"Price" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObjects:sort, nil];
NSArray *sortedArray=[resultArray sortedArrayUsingDescriptors:descriptors];
NSLog(#"Result %# Sorted arr %#",resultArray, sortedArray);
And Output is:
Result (
{
Name = "Black Eyed Peas";
Percentage = 0;
Price = 80;
},
{
Name = "Black Gram";
Percentage = 0;
Price = 56;
},
{
Name = "Channa White";
Percentage = 0;
Price = 100;
},
{
Name = "Double Beans";
Percentage = 0;
Price = 95;
},
{
Name = "Gram Dall";
Percentage = 0;
Price = 100;
},
{
Name = "Green Moong Dal";
Percentage = 0;
Price = 150;
},
{
Name = "Ground Nut";
Percentage = 0;
Price = 140;
},
{
Name = "Moong Dal";
Percentage = 0;
Price = 75;
},
{
Name = "Orid Dal";
Percentage = 0;
Price = 100;
},
{
Name = "Toor Dal";
Percentage = 0;
Price = 150;
}
) Sorted arr (
{
Name = "Channa White";
Percentage = 0;
Price = 100;
},
{
Name = "Gram Dall";
Percentage = 0;
Price = 100;
},
{
Name = "Orid Dal";
Percentage = 0;
Price = 100;
},
{
Name = "Ground Nut";
Percentage = 0;
Price = 140;
},
{
Name = "Green Moong Dal";
Percentage = 0;
Price = 150;
},
{
Name = "Toor Dal";
Percentage = 0;
Price = 150;
},
{
Name = "Black Gram";
Percentage = 0;
Price = 56;
},
{
Name = "Moong Dal";
Percentage = 0;
Price = 75;
},
{
Name = "Black Eyed Peas";
Percentage = 0;
Price = 80;
},
{
Name = "Double Beans";
Percentage = 0;
Price = 95;
}
)
Here The Sorted Array Sorting in some other Order I want to sort this in Ascending order by price.
It's unclear what your test data looks like - but the following snippet works as expected
NSArray *priceArray = [NSArray arrayWithObjects:#(74),#(100),#(100),#(130), nil];
NSArray *nameArray = [NSArray arrayWithObjects:#"Yva",#"Hallo", #"Adam", #"Xavier", nil];
NSMutableArray *resultArray = [NSMutableArray new];
for(int i=0;i<[priceArray count];i++)
{
NSMutableDictionary *cellDict=[[NSMutableDictionary alloc]init];
[cellDict setObject:nameArray[i] forKey:#"Name"];
[cellDict setObject:priceArray[i] forKey:#"Percentage"];
[cellDict setObject:priceArray[i] forKey:#"Price"];
[resultArray addObject:cellDict];
}
// Sort by Name
//NSSortDescriptor *sort =[[NSSortDescriptor alloc] initWithKey:#"Price" ascending:YES];
// Sort by Name
NSSortDescriptor *sort =[[NSSortDescriptor alloc] initWithKey:#"Name" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
NSArray *descriptors = [NSArray arrayWithObjects:sort, nil];
NSArray *sortedArray=[resultArray sortedArrayUsingDescriptors:descriptors];
NSLog(#"Result %# Sorted arr %#",resultArray, sortedArray);
Result:
2015-07-11 12:54:54.358 ret[10480:162783] Result (
{
Name = Yva;
Percentage = 74;
Price = 74;
},
{
Name = Hallo;
Percentage = 100;
Price = 100;
},
{
Name = Adam;
Percentage = 100;
Price = 100;
},
{
Name = Xavier;
Percentage = 130;
Price = 130;
}
) Sorted arr (
{
Name = Adam;
Percentage = 100;
Price = 100;
},
{
Name = Hallo;
Percentage = 100;
Price = 100;
},
{
Name = Xavier;
Percentage = 130;
Price = 130;
},
{
Name = Yva;
Percentage = 74;
Price = 74;
}
)

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"]];

Merge the same objects inside array IOS

I have an array which contains this objects:
(
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 143;
iShiftId = 1;
sItemName = "";
sModifier = "";
},
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 143;
iShiftId = 1;
sItemName = "";
sModifier = "";
},
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 143;
iShiftId = 1;
sItemName = "";
sModifier = "";
},
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 112;
iShiftId = 1;
sItemName = "";
sModifier = "";
}
)
I need to merge the contents of array if the objects are same and modify the object inside that array in such a way that it should be like this:
(
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 3;
iItemDayPriceId = 143;
iShiftId = 1;
sItemName = "";
sModifier = "";
},
{
aOptns = (
);
fCustomDscnt = 0;
fPrcntDscnt = 0;
fPrice = 0;
fQty = 1;
iItemDayPriceId = 112;
iShiftId = 1;
sItemName = "";
sModifier = "";
}
)
As you can see, the entry for object with iItemDayPriceId = 143 becomes 1 only with fQty = 3.
I have tried using the code here: How to Find Duplicate Values in Arrays?
But it is only comparing 2 objects at a time.
Edit: Oops, I missed your count requirement.
Edit 2: And the fact that you wanted to mutate the given array rather the build a new one.
Depends on what you mean by distinct but since it looks like you mean to compare the contents and not the references, you should build a new array so that if the comparison is true you increment the count and otherwise you add the object.
Mutate existing array
Disclaimer: probably not my best work here.
I would appreciate if someone could suggest how to improve this because I am pretty sure it is not the best way to do this and may not even work (don't have access to an Obj-C compiler at the moment).
Foo objectA = [Foo new];
objectA.Bar = #"Bar";
Foo objectB = [Foo new];
objectB.Bar = #"Bar";
Foo objectC = [Foo new];
objectC.Bar = #"Not Bar";
NSMutableArray *array = #[objectA, objectB, objectC];
NSMutableDictionary *countDictionary = [[NSMutableDictionary alloc] init];
for (Foo *foo in [array copy])
{
bool found = false;
for (Foo *key in countDictionary)
{
if ([key isEqualTo:foo])
{
NSNumber *currentCount = [countDictionary objectForKey:key];
int currentIntCount = [currentCount intValue];
currentIntCount++;
[countDictionary setObject:[NSNumber numberWithInt:currentIntCount] forKey:key];
[array removeObject:key];
found = true;
break;
}
if (!found)
[countDictionary setObject:[NSNumber numberWithInt:1] forKey:foo];
}
}
for (Foo *realFoo in array)
{
NSNumber *countNumber = [countDictionary objectForKey:realFoo];
int countInt = [countNumber intValue];
realFoo.Count = countInt;
}
Build new array
Foo objectA = [Foo new];
objectA.Bar = #"Bar";
Foo objectB = [Foo new];
objectB.Bar = #"Bar";
NSMutableArray *array = #[objectA, objectB];
NSMutableArray *distinct = [[NSMutableArray alloc] init];
for (Foo *f in array)
{
bool found = false;
for (Foo *d in distinct)
{
if ([d isEqualTo:f])
{
found = true;
d.Count++;
}
break;
}
if (!found)
[distinct addObject:f];
}
And of course you would have to define an equality comparer for Foos, in this case for instance
-(bool) isEqualTo:(Foo *)nFoo
{
bool isEqual = false;
if ([self.Bar isEqualToString:nFoo.Bar])
isEqual = true;
return isEqual;
}
Having not dealt with Objective C in a while I should say that there may be some best-practices as to implementing equality comparison instead of rolling your own completely like this example
Use below code:
NSMutableArray* myArray =
[[NSMutableArray alloc]initWithObjects:
#"red",#"blue",#"red",#"green",#"yellow", #"33", #"33",#"red", #"123", #"123",nil];
NSOrderedSet *mySet = [[NSOrderedSet alloc] initWithArray:myArray];
myArray = [[NSMutableArray alloc] initWithArray:[mySet array]];
NSLog(#"%#",myArray);

Resources