ios - Sort an NSArray of strings with custom comparator -


i have following array of numbers in strings.

    08,     03,     11,     06,     01,     09,     12,     07,     02,     10 

and want be:

    06,     07,     08,     09,     10,     11,     12,     01,     02,     03 

how can this? thinking of using custom comparator this:

nscomparisonresult compare(nsstring *numberone, nsstring *numbertwo, void *context)  

but never used before.

any help?

kind regards

edit

oké @ moment did this.

   nsarray *unsortedkeys = [self.sectionedkalender allkeys];      nsmutablearray *sortedkeys = [[nsmutablearray alloc]initwitharray:[unsortedkeys sortedarrayusingselector:@selector(localizedcompare:)]]; 

this sorts array 01 --> 12. these numbers represent months in tableview. @ moment starts in januari , stops in december. want is starts in june , ends in march.

hope clears question little bit.

first, write simple comparison function;

nsinteger mysort(id num1, id num2, void *context) {     int v1 = ([num1 intvalue]+6)%12;   // (6+6)%12 0, 6 sorts first.     int v2 = ([num2 intvalue]+6)%12;      if (v1 < v2)      return nsorderedascending;     else if (v1 > v2) return nsordereddescending;     else              return nsorderedsame; } 

then call using sortedarrayusingfunction:context:

nsarray *array = [[nsarray alloc] initwithobjects:       @"08",@"03",@"11",@"06",@"01",@"09",@"12",@"07",@"02",@"10",nil];  nsarray *sortedarray = [array sortedarrayusingfunction:mysort context:null];  nslog(@"%@", sortedarray);  > [06 07 08 09 10 11 12 01 02 03] 

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

node.js - Node - Passport Auth - Authed Post Route hangs on form submission -

Does Firefox offer AppleScript support to get URL of windows? -