Array Ordering of Objective C

Source: Internet
Author: User

Original address: https://my.oschina.net/pengloo53/blog/173810

In general, there are several methods of array ordering commonly used in OC: sortedarrayusingselector:;sortedarrayusingcomparator:;sortedarrayusingdescriptors:

1, simple sort (sortedarrayusingselector:)

If you just sort the string, you can use Sortedarrayusingselector: The method is OK, 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 (@ "Sort after:%@", Sortedarray);
}

Of course, in addition to the use of string compare: Methods, you can write their own compare: methods, the comparison of objects, as follows:

The first is the new person class, which is implemented as follows (header file is saved):

#import "Person.h"
@implementation person

//directly implement the static method, get the Person object
+ (person *) Personwithage with Name and age: ( 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{
  //default by age
    Nscomparisonresult Result = [[[NSNumber NumberWithInt:person.age] Compare:[nsnumber numberwithint:self.age]];//Note: Data conversion for basic data types
  //If Age , sort by name
    if (result = = Nsorderedsame) {result
        = [Self.name compare:person.name];
    }
    Ascending return result
    ;
    Descending
    //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 (@ "Sort after:%@", Sortedarray);
}

2. Use block Syntax (sortedarrayusingcomparator:)

Apple has provided the block syntax, more convenient. Where array sorting can be 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) {

   // Here the code can refer to the above compare: The default sorting method, you can also write the custom method here, to order the object
        nscomparisonresult result = [Obj1 compare:obj2];
        return result;
    };
    NSLog (@ "Sort after:%@", Sortedarray);
}

3, Advanced Sorting (sortedarrayusingdescriptors:)

If this is the case. There is another class variable in the person class, such as the person class, in addition to the name,age variable, and the car type, which has a name attribute. Sorting the person object requires that you sort by the name of the car, if it is the same vehicle, that is, the name of the automobile, and then sort by age, if the age is the same, and then by the name of person.

The above is going to use a third method, using the sort descriptor, not much said, interested to see the API introduction. The code is as follows:

First write a car class, implement class CAR.M code 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 to implement the class PERSON.M code 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;
}

Here, rewrite the description method for the final Test sort result display
-(NSString *) description{return
    [NSString stringwithformat:@ ' age is%zi , the name is%@, the car is%@ ", _age,_name,_car.name];
}

@end

The main function code is as follows:

OrtArray4 () {//First 3 vehicles, Audi, Rolls Royce, bmw car *car1 = [Cars initwithname:@ "Audio"];
        Car *car2 = [car initwithname:@ "Rolls-Royce"];

        Car *CAR3 = [car initwithname:@ "BMW"]; 5 more person, each to send a car, respectively, CAR2, Car1, Car1, car3, car2 person *p1 = [man 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];

        Add array Nsarray *array = [Nsarray arraywithobjects:p1,p2,p3,p4,p5, Nil];
        Constructs the sort 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 in the array and put it in the order you want to sort//I am here: first by age, then by the name of the car, and finally by the name of the person nsarray *descriptorarray = [Nsarray arrayw

        Ithobjects:personagedesc,carnamedesc,personnamedesc, nil];
        Nsarray *sortedarray = [array Sortedarrayusingdescriptors:descriptorarray]; NSLog (@ "%@", Sortedarray);

The results are as follows:

As you can see from the results, sort by age, if the age is the same, by car, if the car is the same, sort by name.

(Note: The above two sorting methods want to implement string display, please rewrite the description method)

Simply try:

    Nsmutablearray *array=[nsmutablearray array];
    for (int i=0; i<5; i++) {
        Dog *d=[[dog alloc]init];
        D.name=[nsstring stringwithformat:@ "Dog%d", I];
        D.age=arc4random ()%10+21;
        [Array addobject:d];
    }

    NSLog (@ "%@", array);
    1 The key is KVC mechanism, can add '. '
    2ascending Controls ascending descending order.
    Nssortdescriptor *sort = [Nssortdescriptor sortdescriptorwithkey:@ "Self.age" ascending:no];
    The previous sentence code is equivalent to this sentence  nssortdescriptor *sort = [nssortdescriptor sortdescriptorwithkey:@ "age" ascending:no];
    Nsarray *arr1 = [array sortedarrayusingdescriptors:@[sort]];
    NSLog (@ "%@", arr1);

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.