Created
March 8, 2014 17:13
-
-
Save PavelGnatyuk/9435201 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface Person : NSObject | |
@property (copy) NSString *firstName; | |
@property (copy) NSString *lastName; | |
- (instancetype)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName; | |
@end | |
@implementation Person | |
- (instancetype)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName | |
{ | |
self = [super init]; | |
if ( self ) { | |
_firstName = [firstName copy]; | |
_lastName = [lastName copy]; | |
} | |
return self; | |
} | |
- (NSString *)description | |
{ | |
return [NSString stringWithFormat:@"%@ %@", _lastName, _firstName]; | |
} | |
@end | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
NSArray *people = @[ [[Person alloc] initWithFirstName:@"Albert" andLastName:@"Einshtein"], | |
[[Person alloc] initWithFirstName:@"Bonapart" andLastName:@"Napoleon"], | |
[[Person alloc] initWithFirstName:@"Michail" andLastName:@"Kutozov"], | |
[[Person alloc] initWithFirstName:@"Georgiy" andLastName:@"Zhukov"], | |
[[Person alloc] initWithFirstName:@"Vladimir" andLastName:@"Nabokov"], | |
[[Person alloc] initWithFirstName:@"Yuri" andLastName:@"Nikulin"], | |
[[Person alloc] initWithFirstName:@"Friedrich" andLastName:@"Nietzsche"] ]; | |
NSLog(@"unsorted: %@", people); | |
// Descriptors | |
NSArray *sortedWithDescriptors = [people sortedArrayUsingDescriptors:@[ [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES], | |
[NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES] ]]; | |
NSLog(@"sortedArrayUsingDescriptors: %@", sortedWithDescriptors); | |
// Comparator | |
NSArray *sortedUsingComparator = [people sortedArrayUsingComparator:^(Person *person1, Person *person2) { | |
NSComparisonResult lastNameComparison = [[person1 lastName] compare:[person2 lastName]]; | |
if (lastNameComparison != NSOrderedSame) | |
return lastNameComparison; | |
return [[person1 firstName] compare:[person2 firstName]]; | |
}]; | |
NSLog(@"sortedArrayUsingComparator: %@", sortedUsingComparator); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment