Saturday, June 1, 2013

NSMutableArray sortUsingComparator example in Objective C (iOS).


NSMutableArray sortUsingComparator

Sorts the array using the comparison method specified by a given NSComparator Block.

- (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;
    }
];

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:@" "]);

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;
}

End of NSMutableArray sortUsingComparator example article.