A summary of the sorting problems of Objective-c Nsarray

Source: Internet
Author: User



This article is from the long458 column, linked to http://blog.csdn.net/long458/article/details/41981273


In general, the commonly used array sorting methods in OC have the following methods: sortedArrayUsingSelector:;sortedArrayUsingComparator:;sortedArrayUsingDescriptors:

1. Simple sorting (sortedArrayUsingSelector:)
If you just sort the strings, you can use the sortedArrayUsingSelector: method, the code is as follows

         //Simple sort
        
 
         void
          sortArray1(){
        
 
             
         NSArray *array = [NSArray arrayWithObjects:@
         "abc"
         ,@
         "456"
         ,@
         "123"
         ,@
         "789"
         ,@
         "ef"
         , nil];
        
 
             
         NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(compare:)];
        
 
             
         NSLog(@
         "After sorting: %@"
         ,sortedArray);
        
 
         }
        
Of course, in addition to using the compare: method that comes with the string, you can also write your own compare: method to compare objects; as follows:
The first is to create a new Person class, the implementation method is as follows (the header file is omitted):

 
         #import "Person.h"
        
 
         @implementation Person
        

           
        
 
         //Directly implement the static method to obtain the Person object with name and age
        
 
         +(Person *)personWithAge:(
         int
         ) age withName:(NSString *)name{
        
 
             
         Person *person = [[Person alloc] init];
        
 
             
         person.age = age;
        
 
             
         person.name = name;
        
 
             
         return
          person;
        
 
         }
        

           
        
 
         //Custom sort method
        
 
         -(NSComparisonResult)comparePerson:(Person *)person{
        
 
           
         //By default sort by age
        
 
             
         NSComparisonResult result = [[NSNumber numberWithInt:person.age] compare:[NSNumber numberWithInt:self.age]];
         //Note: Basic data types need to be converted
        
 
           
         //If the age is the same, sort by name
        
 
             
         if
          (result == NSOrderedSame) {
        
 
                 
         result = [self.name compare:person.name];
        
 
             
         }
        
 
             
         return
          result;
        
 
         }
        

           
        
 
         @end
        
The main function code is as follows:

 
         void
          sortArray2(){
        
 
             
         Person *p1 = [Person personWithAge:23 withName:@
         "zhangsan"
         ];
        
 
             
         Person *p2 = [Person personWithAge:21 withName:@
         "lisi"
         ];
        
 
             
         Person *p3 = [Person personWithAge:24 withName:@
         "wangwu"
         ];
        
 
             
         Person *p4 = [Person personWithAge:24 withName:@
         "liwu"
         ];
        
 
             
         Person *p5 = [Person personWithAge:20 withName:@
         "liwu"
         ];
        
 
             
         NSArray *array = [NSArray arrayWithObjects:p1,p2,p3,p4,p5, nil];
        
 
             
         NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(comparePerson:)];
        
 
             
         NSLog(@
         "After sorting: %@"
         ,sortedArray);
        
 
         }
        
2. Use block syntax (sortedArrayUsingComparator:)
Apple officially provides block syntax, which is more convenient. The array sorting can use the sortedArrayUsingComparator: method, the code is as follows:

 
         void
          sortArray3(){
        
 
             
         NSArray *array = [NSArray arrayWithObjects:@
         "1bc"
         ,@
         "4b6"
         ,@
         "123"
         ,@
         "789"
         ,@
         "3ef"
         , nil];
        
 
             
         NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        

           
        
 
            
         //The code here can refer to the above compare: default sorting method, or you can write a custom method here to sort objects
        
 
                 
         NSComparisonResult result = [obj1 compare:obj2];
        
 
                 
         return
          result;
        
 
             
         }];
        
 
             
         NSLog(@
         "After sorting: %@"
         ,sortedArray);
        
 
         }
        

3. Advanced sorting (sortedArrayUsingDescriptors:)
What if this is the case? There are variables of another class in the Person class. For example, in addition to the name and age variables, the Person class also has a Car type. The Car class has a name attribute. Sort the Person object Order, there is such a requirement: sort according to the name of the car, if it is the same car, that is, the name of the car is the same, then sort by age, if the age is also the same, and finally sort according to the name of the person.

In the above, we will use the third method, using the sorting descriptor, not to mention, if you are interested, you can look at the API introduction. code show as below:

First write a Car class, the implementation of the class Car.m code is as follows:
 
         #import "Car.h"
        
 
         @implementation Car
        

           
        
 
         +(Car *)initWithName:(NSString *)name{
        
 
             
         Car *car = [Car alloc] init];
        
 
             
         car.name = name;
        
 
             
         return
          car;
        
 
         }
        

           
        
 
         @end
        
Then rewrite the Person class, and implement the code of the Person.m class as follows:



         #import "Person.h"
        
 
         #import "Car.h"
        
 
         @implementation Person
        

           
        
 
         +(Person *)personWithAge:(
         int
         )age withName:(NSString *)name withCar:(Car *)car{
        
 
             
         Person *person = [[Person alloc] init];
        
 
             
         person.age = age;
        
 
             
         person.name = name;
        
 
             
         person.car = car;
        
 
             
         return
          person;
        
 
         }
        

           
        
 
         //Rewrite the description method here for the final test sorting result display
        
 
         -(NSString *)description{
        
 
             
         return
          [NSString stringWithFormat:@
         "age is %zi, name is %@, car is %@"
         ,_age,_name,_car.name];
        
 
         }
        

           
        
 
         @end
        
The main function code is as follows:

 
         void
          sortArray4(){
        
 
                 
         //First come 3 cars, Audi, Rolls Royce, BMW
        
 
                 
         Car *car1 = [Car initWithName:@
         "Audio"
         ];
        
 
                 
         Car *car2 = [Car initWithName:@
         "Rolls-Royce"
         ];
        
 
                 
         Car *car3 = [Car initWithName:@
         "BMW"
         ];
        
 
                  
        
 
                 
         //Five more Persons, each will send a car, respectively car2, car1, car1, car3, car2
        
 
                 
         Person *p1 = [Person personWithAge:23 withName:@
         "zhangsan"
          withCar:car2];
        
 
                 
         Person *p2 = [Person personWithAge:21 withName:@
         "zhangsan"
          withCar:car1];
        
 
                 
         Person *p3 = [Person personWithAge:24 withName:@
         "lisi"
          withCar:car1];
        
 
                 
         Person *p4 = [Person personWithAge:23 withName:@
         "wangwu"
          withCar:car3];
        
 
                 
         Person *p5 = [Person personWithAge:23 withName:@
         "wangwu"
          withCar:car2];
        

           
        
 
              
        
 
                 
         //Join the array
        
 
                 
         NSArray *array = [NSArray arrayWithObjects:p1,p2,p3,p4,p5, nil];
        
 
                  
        
 
                 
         //Build a sorting descriptor
        
 
                 
         NSSortDescriptor *carNameDesc = [NSSortDescriptor sortDescriptorWithKey:@
         "car.name"
          ascending:YES];
        
 
                 
         NSSortDescriptor *personNameDesc = [NSSortDescriptor sortDescriptorWithKey:@
         "name"
          ascending:YES];
        
 
                 
         NSSortDescriptor *personAgeDesc = [NSSortDescriptor sortDescriptorWithKey:@
         "age"
          ascending:YES];
        
 
                  
        
 
                 
         //Put the sort descriptor into the array, and the order in which it is put is the order you want to sort
        
 
                 
         //I am here: first sort by age, then by car's name, and finally by person's name
        
 
                 
         NSArray *descriptorArray = [NSArray arrayWithObjects:personAgeDesc,carNameDesc,personNameDesc, nil];
        
 
                  
        
 
                 
         NSArray *sortedArray = [array sortedArrayUsingDescriptors: descriptorArray];
        
 
                 
          NSLog(@
          "%@"
          ,sortedArray);
        
 
          }
        
The results are as follows:


It can be seen from the results that first sort by age, if age is the same, sort by car, if car is the same, sort by name.

(Note: If you want to achieve string display in the above two sorting methods, please override the description method)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.