Merge the same objects inside array IOS - 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);
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++; }
NSDictionary Getting Repeated values
I know this may be a repeated question but I googled a lot but not able to find a suitable answer for me. I have a NSMutableArray which has two NSDictionary with Keys and values which I need to populated on a UITableView. I have retrieved the value of the dictionary which I'm going populate using NSMutableArray *mutArray = [responseArray valueForKey:#"Table"]; And I did like NSMutableSet *names = [NSMutableSet set]; NSMutableArray *mutArray1 = [[NSMutableArray alloc] init]; for (id obj in mutArray) { NSString *destinationName = [obj valueForKey:#"AssetClassName"]; if (![names containsObject:destinationName]) { [mutArray1 addObject:destinationName]; [names addObject:destinationName]; } } Because the value AssetClassName is repeated. Now I have three values in mutArray1 which I need to show as UITableView section. Under AssetClassName I have Some data which determines the row in that section. For retrieving that data I'm doing like for (int i = 0; i < [mutArray1 count]; i++) { NSMutableDictionary *a = [[NSMutableDictionary alloc] init]; NSMutableDictionary *b = [[NSMutableDictionary alloc] init]; for (NSDictionary *dict in mutArray) { if ([[mutArray1 objectAtIndex:i] isEqualToString:[dict valueForKey:#"AssetClassName"]]) { [a setObject:[dict objectForKey: #"SubAssetClassName"] forKey:#"Investment Categories"]; [a setObject:[dict valueForKey:#"Amount"] forKey:#"Amount (EUR)"]; [a setObject:[dict valueForKey:#"AllocationPercentage"] forKey:#"%"]; [a setObject:[dict valueForKey:#"ModelAllocationPercentage"] forKey:#"ModelAllocationPercentage"]; [b setObject:a forKey:[dict valueForKey:#"SubAssetClassName"]]; [mutdict setObject:b forKey:[dict valueForKey:#"AssetClassName"]]; } } } mutdict is a NSMutableDictionary declared globally and is instantiate in viewdidLoad mutdict = [[NSMutableDictionary alloc] init]; The values are inserted into mutdict as I needed. Each SubAssetClassName is added into AssetclassName accordingly. But my problem is in my final dictionary i.e mutdict the values for SubAssetClassName is repeated. Can anybody tell how to solve this. My console "AssetClassName" = { "SubAssetClass" = { "%" = 0; "Amount (EUR)" = 0; "Investment Categories" = "HIGH YIELD BONDS"; "ModelAllocationPercentage" = 22; }; "SubAssetClass" = { "%" = 0; "Amount (EUR)" = 0; "Investment Categories" = "HIGH YIELD BONDS"; "ModelAllocationPercentage" = 22; }; "SubAssetClass" = { "%" = 0; "Amount (EUR)" = 0; "Investment Categories" = "HIGH YIELD BONDS"; "ModelAllocationPercentage" = 22; }; }; "AssetClassName" = { "SubAssetClass" = { "%" = 0; "Amount (EUR)" = 0; "Investment Categories" = "EMERGING MARKETS EQUITIES"; "ModelAllocationPercentage" = 10; }; }; "AssetClassName" = { "SubAssetClass" = { "%" = 0; "Amount (EUR)" = 0; "Investment Categories" = "STRUCTURED PRODUCTS"; "ModelAllocationPercentage" = 10; }; "SubAssetClass" = { "%" = 0; "Amount (EUR)" = 0; "Investment Categories" = "STRUCTURED PRODUCTS"; "ModelAllocationPercentage" = 10; }; "SubAssetClass" = { "%" = 0; "Amount (EUR)" = 0; "Investment Categories" = "STRUCTURED PRODUCTS"; "ModelAllocationPercentage" = 10; }; }; } Here I can see that all SubAssetClass values are same for each section but actually its not. How can I solve this.
You need to create a new instance of your mutable dictionary inside the loop. Right now you create one instance and update it over and over. This results in one dictionary being added over and over. Change you code as follows: for (NSInteger i = 0; i < [mutArray1 count]; i++) { NSMutableDictionary *b = [[NSMutableDictionary alloc] init]; for (NSDictionary *dict in mutArray) { if ([[mutArray1 objectAtIndex:i] isEqualToString:[dict valueForKey:#"AssetClassName"]]) { NSMutableDictionary *a = [[NSMutableDictionary alloc] init]; [a setObject:[dict objectForKey: #"SubAssetClassName"] forKey:#"Investment Categories"]; [a setObject:[dict valueForKey:#"Amount"] forKey:#"Amount (EUR)"]; [a setObject:[dict valueForKey:#"AllocationPercentage"] forKey:#"%"]; [a setObject:[dict valueForKey:#"ModelAllocationPercentage"] forKey:#"ModelAllocationPercentage"]; [b setObject:a forKey:[dict valueForKey:#"SubAssetClassName"]]; [mutdict setObject:b forKey:[dict valueForKey:#"AssetClassName"]]; } } } Also, in most cases you should not be using valueForKey:. Use objectForKey: unless you have a clear and specific need to use key-value coding instead of simply getting an object from the dictionary for a given key.
NSPredicate through nested array using the dictionary key
Could someone help me how to predicate through the below data and retrieve the value for the key "Text". Initially i have dictionary with the below data { ArrayName1 = ( { Target = "<null>"; Text = "Name1"; Value = 1; }, { Target = "<null>"; Text = "Name2"; Value = 2; } ); ArrayName2 = ( { Target = "<null>"; Text = "Name3"; Value = 3; }, { Target = "<null>"; Text = "Name4"; Value = 4; } ); ArrayName3 = ( { Target = "<null>"; Text = "Name5"; Value = 5; }, { Target = "<null>"; Text = "Name6"; Value = 6; } ); ArrayName4 = ( { Target = "<null>"; Text = "somename"; Value = somevalue; } ); ArrayName4 = ( { Target = "<null>"; Text = "somename"; Value = "somevalue"; } ); } I want the end result to be stored in the "resultarray" which should contain value of "Text" key by the search string from all the array and also want to store the corresponding value for the "Value" key in the same array. Thanks, Pradeep
#Dev.RK #Cyph3r - Below are the methods i tried. #Dev.RK,#Cyph3r. I tried the below methods including compound predicate. //Method 1 NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY %K.%K CONTAINS[c] %#", #"Practice",#"Text",searchTextString]; searchArray = [[quickSearchDataDict allValues] filteredArrayUsingPredicate:predicate]; //Method 2 NSPredicate *predicateArray1 = [NSPredicate predicateWithFormat:#"(TEXT==%#)",searchTextString]; NSPredicate * predicateArray2 = [NSPredicate predicateWithFormat:#"SELF.%K.%K contains[c] %#",#"ArrayName2",#"Text",searchTextString]; NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:#[predicateArray1,predicateArray2]]; searchArray = [[quickSearchDataDict allValues] filteredArrayUsingPredicate:predicate];
Try this, hope this will solved your problem- NSMutableDictionary *dict=[[NSMutableDictionary alloc]init]; for (int i=0; i<5; i++) { NSMutableArray *ary=[[NSMutableArray alloc]init]; for (int j=0; j<2; j++) { NSMutableDictionary *dic=[[NSMutableDictionary alloc]init]; [dic setValue:[NSString stringWithFormat:#"none"] forKey:#"Target"]; [dic setValue:[NSString stringWithFormat:#"tst%d",j] forKey:#"Text"]; [dic setValue:[NSString stringWithFormat:#"%d",j+i] forKey:#"Value"]; [ary addObject:dic]; } [dict setObject:ary forKey:[NSString stringWithFormat:#"ArrayName%d",i]]; } NSArray *searchary=[dict valueForKey:[NSString stringWithFormat:#"%#",#"ArrayName0"]]; NSPredicate *pre0 = [NSPredicate predicateWithFormat:#"SELF.%K contains[cd] %#",#"Text", #"tst"]; NSArray *resultArray= [searchary filteredArrayUsingPredicate:pre0]; NSLog(#"%#",resultArray); here is the log- 1. Text==tst0 ( { Target = none; Text = tst0; Value = 0; } ) 2. Text==tst ( { Target = none; Text = tst0; Value = 0; }, { Target = none; Text = tst1; Value = 1; } ) and this is complete data- { ArrayName0 = ( { Target = none; Text = tst0; Value = 0; }, { Target = none; Text = tst1; Value = 1; } ); ArrayName1 = ( { Target = none; Text = tst0; Value = 1; }, { Target = none; Text = tst1; Value = 2; } ); ArrayName2 = ( { Target = none; Text = tst0; Value = 2; }, { Target = none; Text = tst1; Value = 3; } ); ArrayName3 = ( { Target = none; Text = tst0; Value = 3; }, { Target = none; Text = tst1; Value = 4; } ); ArrayName4 = ( { Target = none; Text = tst0; Value = 4; }, { Target = none; Text = tst1; Value = 5; } ); }
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.
I'd like to store image,name,price in one array and if I sort the price value then name and image have to arrange properly
I am storing those three datas in to one, if user likes to sort the by the price then, everything should be in order. Please help me to show it like that. imgArr =[[NSArray alloc]init]; nameArr=[[NSArray alloc]init]; priceArr=[[NSArray alloc]init]; Json script that I've used like this. { image = ""; name = Blue; "option_value_id" = 40; price = 3; "price_prefix" = "+"; "product_option_value_id" = 3; quantity = 300; subtract = 0; weight = 3; "weight_prefix" = "+"; }, { image = ""; name = Green; "option_value_id" = 41; price = 1; "price_prefix" = "+"; "product_option_value_id" = 1; quantity = 100; subtract = 0; weight = 1; "weight_prefix" = "+"; }, { image = ""; name = Yellow; "option_value_id" = 42; price = 2; "price_prefix" = "+"; "product_option_value_id" = 2; quantity = 200; subtract = 1; weight = 2; "weight_prefix" = "+"; }
Store all these dictionaries in one array and sort this array by any field- -(NSArray *)sortArrayByPrice:(NSArray *)originalArray{ NSSortDescriptor *sortByPrice = [NSSortDescriptor sortDescriptorWithKey:#"price" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortByPrice]; NSArray *sortedArray = [originalArray sortedArrayUsingDescriptors:sortDescriptors]; return sortedArray; }