NSArray sortedArrayUsingComparator
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr
Parameters
cmptr
A comparator block.
Return Value of [NSArray sortedArrayUsingComparator]
An array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified cmptr.
NSArray sortedArrayUsingComparator example.
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}];
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}];
Example of [NSArray sortedArrayUsingComparator].
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSDate *first = [(Person*)a birthDate];
NSDate *second = [(Person*)b birthDate];
return [first compare:second];
}];
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSDate *first = [(Person*)a birthDate];
NSDate *second = [(Person*)b birthDate];
return [first compare:second];
}];
NSArray sortedArrayUsingComparator example.
NSArray *arrayToSort = where ever you get the array from... ;
NSComparisonResult (^sortBlock)(id, id) = ^(id obj1, id obj2) {
if ([obj1 position] > [obj2 position]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 position] < [obj2 position]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
};
NSArray *sorted = [arrayToSort sortedArrayUsingComparator:sortBlock];
NSComparisonResult (^sortBlock)(id, id) = ^(id obj1, id obj2) {
if ([obj1 position] > [obj2 position]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 position] < [obj2 position]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
};
NSArray *sorted = [arrayToSort sortedArrayUsingComparator:sortBlock];