Ordering iOS Basics

Source: Internet
Author: User

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

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.