1. String comparisons
1 -(Nscomparisonresult) Compare: (NSString *) str;
For example:
1 @" Zhangsan " ; 2 @" Susan " ; 3 nscomparisonresult result = [str1 compare:str2];
2. Custom sorting of arrays
1 nsarray *arr = [Nsarray array]; 2 [arr sortusingselector: @selector (custom comparison method)];
The custom comparison method here is designed in reference to the Compare: Method in NSString.
For example, design a student class that contains the name and age two properties, and if you are designing a method that compares the ages, the code is as follows:
The code declaration is:
1 -(Nscomparisonresult) Comparestudent: (Student *) s;
The code is implemented as:
1-(Nscomparisonresult) Comparestudent: (Student *) s {2 if(Self.age >s.age) {3 returnnsordereddescending;4}Else if(Self.age <s.age) {5 returnnsorderedascending;6}Else{7 returnNsorderedsame;8 }9}
Note: the Declaration and implementation of the above methods are all implemented in the student class.
The code to invoke the comparison method is:
1 [arr sortusingselector: @selector (comparestudent:)];//arr stores n student objects
3. Array sorting for multi-attribute comparisons
1 // Descriptor: The first parameter represents the name of the property to be compared, the second argument is yse as ascending, otherwise descending 2 nssortdescriptor *agedes = [nssortdescriptor sortdescriptorwithkey:@ "Age" Ascending:yes]; 3 nssortdescriptor *namedes = [nssortdescriptor sortdescriptorwithkey:@ "name" Ascending:yes]; 4 [arr Sortusingdescriptors:@[agedes,namedes]]; // sort by age, then by first name
Ordering iOS Basics