Sorting of objects in the array (sort) and sorting of array objects (sort)

Source: Internet
Author: User

Sorting of objects in the array (sort) and sorting of array objects (sort)

1. There are many methods for sorting arrays, such as for and while loop to perform Bubble sorting or multiple sorting methods such as quick view and sorting.

Here I want to talk about several system methods provided by Apple API.

A. iterator Descriptor

B. Comparison of Selector Methods

C. Function Comparison Function

D. Block Code Block Customization

2. Example

1.1 A Class (Person) for object comparison)

123456789 @interface Person : NSObject @property(nonatomic copy)NSString * name; @property(nonatomic copy)NSString * phone; @property(nonatomic , assign)int age; @end

1.2 customize several Person objects (in other classes)

1234567891011121314151617 Person *person1 = [[Person alloc] init];person1.name = @"gulong";person1.age = 23; Person *person2 = [[Person alloc] init];person2.name = @"guzheng";person2.age = 24; Person *person3 = [[Person alloc] init];person3.name = @"zhangsan";person3.age = 21; Person *person4 = [[Person alloc] init];person4.name = @"lisi";person4.age = 25; NSArray *originalArray = @[person1,person2,person3,person4];

1.3 sorting starts

1.3.1 use iterator for sorting

You can use NSSortDescriptor to conveniently sort multiple conditions.

123 NSSortDescriptor *sorter1 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];NSSortDescriptor *sorter2 = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:NO];NSArray *modifyArray1 = [originalArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sorter1,sorter2,nil]];

// First sort by name letters in ascending order, and then compare the age size to sort in descending order

// The array can be sorted multiple times through sortedArrayUsingDescriptors (that is, the next comparison iterator is performed when the values are equal)

1.3.2 sort by SEL

First, you need to define in the object class and implement this method (OC method) in the Implementation class. This method returnsThe enumerated value of NSComparisonResult (actually-, 1), and then NSArray callsSortedArrayUsingSelector

1 Person.h<br>- (NSComparisonResult)compareAgeAscende:(id)other;
12345678910111213 Person.m<br>- (NSComparisonResult)compareAgeAscende:(id)other{    Person *otherPerson = (Person *)other;    if (self.age > otherPerson.age) {        return NSOrderedDescending;    }else{        if (self.age == otherPerson.age) {            return NSOrderedSame;        }else{            return NSOrderedAscending;        }    }}

The following code calls sortedArrayUsingSelector.

123 ViewController  (- (void)viewDidLoad)  NSArray *modifyArray2 = [originalArray sortedArrayUsingSelector:@selector(compareAgeAscende:)];  NSLog(@"modifyArray2 : %@",modifyArray2);

Note:A. When the object in the array is NSString, use compare: for sel comparison.

1.3.3 compared to a function, this function is a comparison function (C language). This function also puts back the NSComparisonResult enumeration, which is actually an integer of NSInteger,Then NSArray callsSortedArrayUsingFunction is compared and sorted internally.

123456 // Defined in viewController (in fact, it doesn't matter where it is defined, but it can be called only on the line)NSInteger personSort(id obj1,id obj2 ,void * context){    Person *person1 = (Person *)obj1;    Person *person2 = (Person *)obj2;    return [person1.name localizedCompare:person2.name];}

 

12 NSArray *modifyArray3 = [originalArray sortedArrayUsingFunction:personSort context:NULL];    NSLog(@"modifyArray3 : %@",modifyArray3);

1.3.4 The block compares the block definitions and writes a comparison code block. The code block also returns the NSComparisonResult enumeration.

123456789101112 NSArray *modifyArray4 = [originalArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {        Person *pers1 = (Person *)obj1;        Person *pers2 = (Person *)obj2;        if (pers1.age > pers2.age) {            return NSOrderedDescending;        }else if (pers1.age < pers2.age){            return NSOrderedAscending;        }else{            return NSOrderedSame;        }    }];    NSLog(@"modifyArray4 : %@",modifyArray4);

1.4 string (with Chinese characters) to PinYin string (for the above comparison problem, for more needs)

123456 - (NSString *) phonetic:(NSString*)sourceString {    NSMutableString *source = [sourceString mutableCopy];    CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO);    CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO);    return source;}<br>  // Chinese characters are separated by spaces after being converted to PinYin

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.