objective c - SortedArrayUsingComparator not working accurately -


i trying sort array, seems not work reliably.

here code sorting. request priorityid has values 1-5 example: enter image description here

 sortedarray = [self.selectedreqarray sortedarrayusingcomparator:^nscomparisonresult(id a, id b) {             nslog(@"value a: %@", [nsnumber numberwithinteger:[(request*)a priorityid]]);             nslog(@"value b %@", [nsnumber numberwithinteger:[(request*)b priorityid]]);             nsnumber *first = [nsnumber numberwithint:[(request*)a priorityid]];             nsnumber *second = [nsnumber numberwithint:[(request*)b priorityid]];             return [first compare:second];         }];          self.sortedreqarray = [nsmutablearray arraywitharray:sortedarray]; 

sometimes it's sorting correctly 1-5, sorts 1 2 4 5 3...

then when go take @ nslog it's spitting out big values when should 1-5.

here sample output value b 168492640 value a: 168492640 value b 168492640 value a: 174580912 value b 168492640 value a: 174580912 value b 168492640 value a: 174580912 value b 168492640 value a: 174580912 value b 168492640 value a: 174580912

what happening? thank you!

from debugger display [(request*)a priorityid] seems nsnumber, treating integer (so comparing addresses of objects).

this following should work:

sortedarray = [self.selectedreqarray sortedarrayusingcomparator:^nscomparisonresult(id a, id b) {             nsnumber *first = [(request*)a priorityid];             nsnumber *second = [(request*)b priorityid];             return [first compare:second];         }]; 

a perhaps more elegant way write is

sortedarray = [self.selectedreqarray sortedarrayusingcomparator:^nscomparisonresult(request* a, request* b) {             nsnumber *first = [a priorityid];             nsnumber *second = [b priorityid];             return [first compare:second];         }]; 

if request class key-value coding compliant key priorityid, following should work:

nssortdescriptor *sort = [nssortdescriptor sortdescriptorwithkey:@"priorityid" ascending:yes]; sortedarray = [self.selectedreqarray sortedarrayusingdescriptors:@[sort]]; 

Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -