system type sorting;
Nsarray *goodsnames [Email protected][@ "Computer" @ "iphone" @ "ipad"];
Nsarray *sortedarray=[goodsnames sortedarrayusingselector: @selector (compare:)];
Custom sorting
Person *p1=[[person alloc]initwithname:@ "Tom" Andage:12 Andcard:nil];
Person *p2=[[person alloc]initwithname:@ "Jack" andage:23 Andcard:nil];
Person *p1=[[person alloc]initwithname:@ "Maggie" Andage:11 Andcard:nil];
Nsarry *[email PROTECTED][P1,P2,P3];
Define a Compareperson method in the person class
/***************************************************************
-(Nscomparisonresult) Compareperson: (person *) person
{
NSNumber *age1=[[nsnumber Alloc]initwithint:self.age];
NSNumber *age2=[[nsnumber Alloc]initwithint:person.age];
Nscomparisonresult Result=[age1 Compare:age2];
if (result = = Nsorderedsame)
{
Result=[self.name Compare:person.name];
}
return result;
}
/******************************************************************
Nsarray *[email PROTECTED][P1,P2,P3];
Nsarray *sortedarray=[personsarray sortedarrayusingselector: @selector (Compareperson:)];
Finish sorting the Personsarray
Sorting by using block
Nsarray *sortedarray=[personsarray sortedarrayusingcomparator:^nscomparisonresult (id obj1,id obj2) {
Person *p1= (person *) obj1;
Person *p2= (person *) obj2;
NSNumber *age1=[[nsnumber Alloc]initwithint:self.age];
NSNumber *age2=[[nsnumber Alloc]initwithint:person.age];
Nscomparisonresult Result=[age1 Compare:age2];
if (result = = Nsorderedsame)
{
Result=[self.name Compare:person.name];
}
return result;
}
Complex sorting
Nssortdescriptor
Nssortdescriptor *sort1=[[nssortdescriptor]initwithkey:@ "name" Ascending:yes];
Nssortdescriptor *sort2=[[nssortdescriptor]initwithkey:@ "age" ascending:yes];
Nsarray *[email Protected][sort1,sort2];
Nsarray *sortedarray =[personsarray Sortedarrayusingdescriptors:conditionsarray];
/*******************
Nssortdescriptor *sort1=[[nssortdescriptor]initwithkey:@ "name" Ascending:yes];
Nssortdescriptor *sort2=[[nssortdescriptor]initwithkey:@ "Self.card.balance" ascending:yes];
object-c-foundation-Array Sorting