distinctUnionOfObjects changes the order of an array - ios

Below is my original array :
{
FilePath = "Selfcare.jpg";
ModuleId = 18;
ModuleName = "Infant N Toddler";
SkillLevelID = 59;
SkillLevelName = "Self Care";
},
{
FilePath = "Preschool.jpg";
ModuleId = 18;
ModuleName = "Infant N Toddler";
SkillLevelID = 60;
SkillLevelName = "Preschool Readiness";
},
{
FilePath = "Learning_Primary.jpg";
ModuleId = 22;
ModuleName = Cognitive;
SkillLevelID = 71;
SkillLevelName = "Learning Readiness - Primary Skills";
},
{
FilePath = "PreAcad_Primary.jpg";
ModuleId = 22;
ModuleName = Cognitive;
SkillLevelID = 72;
SkillLevelName = "Pre-Academics: Primary Skills";
}
when I apply distinctUnionOfObjects
NSArray *curriculums = [array valueForKeyPath:#"#distinctUnionOfObjects.ModuleName"];
this changes the order giving me resulting array
<__NSArrayI>(
Cognitive,
Infant N Toddler
)
It should give
<__NSArrayI>(
Infant N Toddler,
Cognitive
)
as per original array order.
How do I restrict this order change?

please try this one
NSArray *orderedSet = [[NSOrderedSet orderedSetWithArray:[people valueForKey:#"ModuleName"]] array];

Related

Realm throws error when trying to add and save object

I'm developing iOS app with Realm library and it works fine.
But when I tried to save one model it throws error like this.
Terminating app due to uncaught exception 'RLMException', reason:
'Target table row index out of range
Here's code.
....
do {
try realm?.write {
let newPatientImage = PatientImage()
newPatientImage.path = imageName
if let flap = flap {
newPatientImage.setStronglyTypedFlap(flap)
}
newPatientImage.hasPhoto = hasPhoto
newPatientImage.flap?.flapLocationRaw = flapLocation.rawValue
newPatientImage.id = newPatientImage.incrementalID()
patient.patientImages.append(newPatientImage)
realm?.add(newPatientImage)
realm?.add(patient, update: true)
}
} catch {
}
...
Here's newPatientImage object.
PatientImage {
id = 22;
hasPhoto = 0;
isPostOp = 0;
path = 4426699712;
date = 2019-04-26 11:32:15 +0000;
flap = RhomboidAFlap {
id = 1;
name = Rhomboid A;
adjustables = List<Adjustable> <0x280b5c120> (
[0] Adjustable {
value = 60;
defaultValue = 60;
name = A;
isDegrees = 1;
},
[1] Adjustable {
value = 60;
defaultValue = 60;
name = B;
isDegrees = 1;
},
[2] Adjustable {
value = 200;
defaultValue = 200;
name = C;
isDegrees = 0;
},
[3] Adjustable {
value = 200;
defaultValue = 200;
name = E;
isDegrees = 0;
}
);
a = 0.6491648060943035;
b = 0;
c = 0;
d = 0.6491648060943035;
tx = -195.6666717529297;
ty = -144.5;
xOffset = -44.99840983089462;
yOffset = 30.7939660691552;
width = 650;
height = 1000;
centerX = 429.5;
centerY = 499.9999999999999;
calibrationSettings = CalibrationSettings {
measurementUnitRaw = px;
conversionRatio = 1;
measuredLength = 0;
startX = 0;
startY = 0;
endX = 0;
endY = 0;
};
flapLocationRaw = ;
};
ohPlastyFlap = (null);
curvelinearFlap = (null);
rhomboidAFlap = RhomboidAFlap {
id = 1;
name = Rhomboid A;
adjustables = List<Adjustable> <0x280b5c120> (
[0] Adjustable {
value = 60;
defaultValue = 60;
name = A;
isDegrees = 1;
},
[1] Adjustable {
value = 60;
defaultValue = 60;
name = B;
isDegrees = 1;
},
[2] Adjustable {
value = 200;
defaultValue = 200;
name = C;
isDegrees = 0;
},
[3] Adjustable {
value = 200;
defaultValue = 200;
name = E;
isDegrees = 0;
}
);
a = 0.6491648060943035;
b = 0;
c = 0;
d = 0.6491648060943035;
tx = -195.6666717529297;
ty = -144.5;
xOffset = -44.99840983089462;
yOffset = 30.7939660691552;
width = 650;
height = 1000;
centerX = 429.5;
centerY = 499.9999999999999;
calibrationSettings = CalibrationSettings {
measurementUnitRaw = px;
conversionRatio = 1;
measuredLength = 0;
startX = 0;
startY = 0;
endX = 0;
endY = 0;
};
flapLocationRaw = ;
};
rhomboidBFlap = (null);
noteFlap = (null);
vyPlastyFlap = (null);
bilobedFlap = (null);
circularZFlap = (null);
atPlastyFlap = (null);
ouPlastyAFlap = (null);
ouPlastyBFlap = (null);
simpleEllipseFlap = (null);
}
And Here's patient object.
Patient {
id = 1;
firstName = Gg;
lastName = ;
email = ;
phone = ;
address1 = ;
address2 = ;
city = ;
state = ;
dateOfBirth = 2019-04-03 21:24:28 +0000;
medicalRedcordNumber = ;
imageUrl = avatar_1;
patientImages = List<PatientImage> <0x2834a5200> (
[0] PatientImage {
id = 1;
hasPhoto = 1;
isPostOp = 0;
path = 4489901936;
date = 2019-04-08 16:21:54 +0000;
flap = (null);
ohPlastyFlap = (null);
curvelinearFlap = (null);
rhomboidAFlap = (null);
rhomboidBFlap = (null);
noteFlap = (null);
vyPlastyFlap = (null);
bilobedFlap = (null);
circularZFlap = (null);
atPlastyFlap = (null);
ouPlastyAFlap = (null);
ouPlastyBFlap = (null);
simpleEllipseFlap = (null);
}
}
Could anyone please help me resolve this issue?
This issue doesn't happen before updating iOS version and Realm version.
Thanks.
You need to manipulate realm in a write transaction like this:
do {
try self.realm.write
{
self.realm.add(entity, update: update)
}
}
catch {}
It was because every Flap classes(like ohPlastyFlap, curvelinearFlap ...) override Flap class and Realm doesn't recognize Flap type.
I fixed it by correctly setting Flap type.
The "patient" object is missing the corresponding initialization, which is still a nil.
Before
patient.patientImages.append(newPatientImage)
try creating for "patient".

how to store that json data into array, after using jsonserialization iam getting that data

let jsonResult1:NSDictionary = NSJSONSerialization.JSONObjectWithData(da!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
println(jsonResult1)
getting below data in console
{
0 = {
"consulting_dr" = "DR.Appaji .";
"current_bed_nr" = 0;
"current_room_nr" = 0;
"discharge_date" = "03/03/2015 00:00";
"encounter_date" = "02/03/2015 12:45";
"encounter_nr" = 201503024000;
info = "";
"item_description" = "";
name = "Mrs. mythily S";
pdob = "01/08/1976";
pid = 100004;
psex = f;
pyear = "38 Years";
};
1 = {
dosage = 1;
drdate = "25/08/2014";
drnotes = "";
drugclass = Tablet;
duration = "5 day";
frequency = "";
medicine = "ACECLOFENAC+PARACETAMOL";
route = Oral;
tcomplients = "";
};
2 = {
BMI = "A:1:{s:4:\"SPO2\";s:1:\"1\";}";
BSA = "A:1:{s:4:\"SPO2\";s:1:\"1\";}";
"Dystolic_bp" = 29;
Height = 24;
Pulse = 26;
Respiration = 27;
"Systolic_bp" = 28;
Temp = 25;
Weight = 22;
dosage = 1;
drdate = "25/08/2014";
drnotes = "";
drugclass = Tablet;
duration = "5 day";
frequency = "";
medicine = RABEPRAZOLE;
route = Oral;
tcomplients = "";
};
}
how to store this in array
That is a Dictionary. It is easy to get just the data without the keys.
In Objective-C it would be :
NSArray *allData = [jsonResult1 allValues];
For swift it should be like: (not sure about syntax)
var allData = jsonResult1.allValues()
If you're up for it, you should give SwiftyJSON a try.
https://github.com/SwiftyJSON/SwiftyJSON
I've recently used it for an application that deals with a ton of JSON responses from a web service and SwiftyJSON has made it super easy for me to deal with JSON data in Swift. It will convert NSData to Dictionaries or Arrays seamlessly for you.

How to create a sub NSArray that includes key-value pairs?

I have the following NsArray and I want to sort it and create a sub array that include specific key-value pairs.
{
scores = (
{
category = 2;
"league_code" = epl;
"team_away" = Everton;
"team_home" = Liverpool;
},
{
category = 2;
"league_code" = epl;
"team_away" = Fulham;
"team_home" = "Swansea City";
},
{
category = 3;
"league_code" = ita;
"team_away" = Torino;
"team_home" = Milan;
},
{
category = 3;
"league_code" = ita;
"team_away" = Lazio;
"team_home" = Juve;
}
}
}
and I would like to create a new array or just modify array to include only objects with "league_code" = epl key.
So I want to get
{
scores = (
{
category = 2;
"league_code" = epl;
"team_away" = Everton;
"team_home" = Liverpool;
},
{
category = 2;
"league_code" = epl;
"team_away" = Fulham;
"team_home" = "Swansea City";
}
}
}
I tried to convert it to use dictionaryWithObjects:forKeys but it didn't work.
NSMutableArray* newArray = [NSMutableArray array];
NSArray* oldArray = outerDictionary[#"scores"];
for (NSDictionary* dictEntry in oldArray) {
NSString* leagueCode = dictEntry[#"league_code"];
if ([leagueCode isEqualToString #"epl"]) {
[newArray addObject:dictEntry];
}
}
Was that all that hard?
Loop Through and the if it matches your conditions add it to a dictionary. I recommend the for-loop but any loop while do.

sorting a JSON return into UITableView Sections and Rows

I'm trying to sort a JSON return into multiple sections according to each day. Here is the JSON return,
sales = (
{
"dis_dollars" = 0;
"dis_percent" = 0;
id = 111;
saleDay = 5;
saleMonth = 1;
saleTime = "20:02:39";
saleYear = 2014;
"total_price" = 25;
},
{
"dis_dollars" = 0;
"dis_percent" = 0;
id = 103;
saleDay = 2;
saleMonth = 1;
saleTime = "19:13:41";
saleYear = 2014;
"total_price" = 79;
},
{
"dis_dollars" = "0.55";
"dis_percent" = "0.10000000149012";
id = 101;
saleDay = 2;
saleMonth = 1;
saleTime = "10:41:11";
saleYear = 2014;
"total_price" = 22;
},
{
"dis_dollars" = 0;
"dis_percent" = 0;
id = 108;
saleDay = 1;
saleMonth = 1;
saleTime = "11:00:00";
saleYear = 2014;
"total_price" = 66;
}
);
}
I can get the number of sections if I do it this way
//...Connect to php script and get return json object
int saleDay = 0;
//Loop through json return
for (int i = 0;i < [sales count]; i++) {
NSDictionary* dict = [sales objectAtIndex:i];
Sale *eachSale =[[Sale alloc] initWithSaleId:[dict valueForKey:#"id"]
saleDay:[dict valueForKey:#"saleDay"]
saleMonth:[dict valueForKey:#"saleMonth"]
saleYear:[dict valueForKey:#"saleYear"]
saleTime:[dict valueForKey:#"saleTime"]
saleTotal:[dict valueForKey:#"total_price"]
saleDisDollars:[dict valueForKey:#"dis_dollars"]
saleDisPercent:[dict valueForKey:#"dis_percent"]];
NSLog(#"sale Day %#",eachSale.saleDay);
[_salesList addObject:eachSale];
int eachSaleDay = [eachSale.saleDay intValue];
// if the next day is different from the one before it, add a new section.
if (saleDay != eachSaleDay) {
_saleDaysCount += 1;
NSLog(#"eachSaleDay %i" ,eachSaleDay);
NSLog(#"salesDayCount %i" ,_saleDaysCount);
}
saleDay = eachSaleDay;
}
This will give me the correct number of sections, but how do I group the objects according to the day to find out the number of rows for each section, and what objects should go in each row?
I think I need to use NSSort Descriptors but I'm not sure where I would implement it and how to access the individual day arrays.
Any suggestions?
Thanks
I would simply add an additional field of type NSNumber with the complete date for each Sale while you are looping through your results.
eachSale.saleDateIdentifier = #(eachSale.saleYear.intValue * 10000 +
eachSale.saleMonth.intValue * 100 +
eachSale.saleDay.intValue);
Now it is easy to sort and count:
[_salesList sortUsingDescriptors:
#[[NSSortDescriptor sortDescriptorWithKey:#"saleDateIdentifier" ascending:NO]]];
NSArray *allDates = [_salesList valueForKeyPath:#"saleDateIdentifier"];
NSSet *uniqueDates = [NSSet setWithArray:allDates];
NSArray *sortedUniqueDates = [uniqueDates sortedArrayUsingDescriptors:
#[[NSSortDescriptor sortDescriptorWithKey:#"saleDateIdentifier" ascending:NO]]];
Your number of sections is sortedUniqueDates.count. For each section you could use the saleDateIdentifier to format the date string in titleForRowAtIndexPath.
BTW, maybe you do not want to use valueForKey in your init method for eachSale. Maybe you actually mean objectForKey. Better even, you should type the properties of the Sale class and use NSNumber and NSString as appropriate.

iphone sdk+How to retrive dictionary inside array of dictionary values

i want to retrive KpiName key(KpiData is array inside kpiName is dictionary key) and my data structure mentioned below
--Array of dictionaries inside array of dictinary
ex..listOfProjectsArray--(
{
alertSeverity = 1;
customerName = TPMG;
endDate = "05-05-2013";
isProjectHide = 1;
kpiData = (
{
KpiName = "Change Request ";
kpiActual = 14;
kpiPlanned = "";
kpiUnit = "";
},
{
KpiName = "Aged Debit";
kpiActual = 24000;
kpiPlanned = "";
kpiUnit = EUR;
},
);
lastInvoiceDate = "05-04-2013";
nextBillingDate = "05-04-2013";
nextMilestoneDate = "10-04-2013";
nextReviewDate = "08-04-2013";
plannedCompletionDate = "04-05-2013";
projectID = 3000;
projectName = "Rain Harvesting";
projectSortType = "";
projectStatus = 1;
startDate = "01-01-2013";
},
i tried this one but its returning null
NSString *kpiName = [[[[listOfProjectsArray objectAtIndex:indexPath.row] valueForKey:#"kpiData"] objectAtIndex:0]valueForKey:#"kpiName"];
NSLog(#"kpiname:%#", kpiName);
Try this
NSString *kpiName =[[[[listOfProjectsArray objectAtIndex:indexPath.row] objectForKey:#"kpiData"]objectAtIndex:0]objectForKey:#"KpiName"];
I was mentioned wrong dictionary key
NSString *kpiName = [[[[listOfProjectsArray objectAtIndex:indexPath.row] valueForKey:#"kpiData"] objectAtIndex:0]valueForKey:#"kpiName"];
NSLog(#"kpiname:%#", kpiName);
correct one is KpiName key instead of kpiName.

Resources