ios - ordering array with another array -
i have following categorynames array.
and now, have categorytempelements , has cname property. need know how order categorytempelements order of categorynames.
update: have added sortorder property category object , tried following order not change.
for (category* in categorytempelements) { int index = (int)[categorynames indexofobject:a.cname]; a.sortorder = index; } nssortdescriptor *sortdescriptor = [[nssortdescriptor alloc] initwithkey:@"sortorder" ascending:yes]; nsarray *sortdescriptors = [nsarray arraywithobject:sortdescriptor]; nsarray *sortedarray = [categorytempelements sortedarrayusingdescriptors:sortdescriptors];
you need first convert categorynames array dictionary nsstring key , nsnumber int value, value order in array
//this example code, first array (reference value array) nsarray * array = @[@"prueba",@"prueba2",@"prueba3"]; //first need convert array in nsdictionary nsmutabledictionary * arraydict = [nsmutabledictionary dictionary]; int counter = 0; (nsstring * value in array) { if(arraydict[value] == nil) { arraydict[value] = [nsnumber numberwithint:counter]; } counter++; } after can value , order sortedarrayusingcomparator method, this
//this example of second array categorytempelements nsarray * arrayofobjs = @[[testobject testobjectwithname:@"prueba3"],[testobject testobjectwithname:@"prueba"],[testobject testobjectwithname:@"prueba2"]]; nsarray * sorted = [arrayofobjs sortedarrayusingcomparator:^nscomparisonresult(testobject * _nonnull obj1, testobject * _nonnull obj2) { if([((nsnumber*)arraydict[obj1.cname]) intvalue] < [((nsnumber*)arraydict[obj2.cname]) intvalue]){ return nsorderedascending; } if([((nsnumber*)arraydict[obj1.cname]) intvalue] > [((nsnumber*)arraydict[obj2.cname]) intvalue]){ return nsordereddescending; } return nsorderedsame; }]; (testobject * obj in sorted) { nslog(@"%@",obj.cname); } and voila in sorted have array of object sorted first array nsstring order
hope helps


Comments
Post a Comment