NSMutableArray sortUsingComparator
- (void)sortUsingComparator:(NSComparator)cmptr
Parameters of [NSMutableArray sortUsingComparator]
cmptr
A comparator block.
NSMutableArray sortUsingComparator example.
[persons sortUsingComparator:
^NSComparisonResult(id obj1, id obj2){
Person *p1 = (Person*)obj1;
Person *p2 = (Person*)obj2;
if (p1.personAge > p2.personAge) {
return (NSComparisonResult)NSOrderedDescending;
}
if (p1.personAge < p2.personAge) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}
];
^NSComparisonResult(id obj1, id obj2){
Person *p1 = (Person*)obj1;
Person *p2 = (Person*)obj2;
if (p1.personAge > p2.personAge) {
return (NSComparisonResult)NSOrderedDescending;
}
if (p1.personAge < p2.personAge) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}
];
Example of [NSMutableArray sortUsingComparator].
[persons sortUsingComparator:
^NSComparisonResult(id obj1, id obj2)
{
Person *p1 = (Person*)obj1;
Person *p2 = (Person*)obj2;
if (p1.personAge < p2.personAge)
return NSOrderedAscending;
if (p1.personAge > p2.personAge)
return NSOrderedDescending;
return NSOrderedSame;
}];
NSLog(@"%@", [persons componentsJoinedByString:@" "]);
^NSComparisonResult(id obj1, id obj2)
{
Person *p1 = (Person*)obj1;
Person *p2 = (Person*)obj2;
if (p1.personAge < p2.personAge)
return NSOrderedAscending;
if (p1.personAge > p2.personAge)
return NSOrderedDescending;
return NSOrderedSame;
}];
NSLog(@"%@", [persons componentsJoinedByString:@" "]);
NSMutableArray sortUsingComparator example.
[array sortUsingComparator: ^(id a, id b) {
if ( a.newsID < b.newsID) {
return (NSComparisonResult)NSOrderedAscending;
} else if ( a.newsID > b.newsID) {
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}
if ( a.newsID < b.newsID) {
return (NSComparisonResult)NSOrderedAscending;
} else if ( a.newsID > b.newsID) {
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}