Saturday, June 1, 2013

NSMutableArray sortUsingFunction context example in Objective C (iOS).

NSMutableArray sortUsingFunction context

Sorts the array’s elements in ascending order as defined by the comparison function compare.

- (void)sortUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context

Parameters of [NSMutableArray sortUsingFunction context]
The comparison function to use to compare two elements at a time.
The function's parameters are two objects to compare and the context parameter, context. The function should return NSOrderedAscending if the first element is smaller than the second, NSOrderedDescending if the first element is larger than the second, and NSOrderedSame if the elements are equal.
The context argument to pass to the compare function.

Discussion of [NSMutableArray sortUsingFunction context]
This approach allows the comparison to be based on some outside parameter, such as whether character sorting is case-sensitive or case-insensitive.

NSMutableArray sortUsingFunction context example.

 -(void) orderByProximityFromLocation:(CLLocationCoordinate2D) coordinates
CLLocation* currentLocation = [[CLLocation alloc] initWithLatitude:coordinates.latitude longitude:coordinates.longitude];
[listOfPOI sortUsingFunction:compareDistance context:currentLocation];
[currentLocation release];


Example of [NSMutableArray sortUsingFunction context].
Close analogue using NSMutableArray:

[opponentMatchDicts sortUsingFunction:compareMatchByDate context:nil];

static int compareMatchByDate( id m1, id m2, void *context)
    NSDictionary *mDict1 = (NSDictionary *) m1;
    NSDictionary *mDict2 = (NSDictionary *) m2;
    NSDate *date1 = [mDict1 objectForKey:kMatchNSDate];
    NSDate *date2 = [mDict2 objectForKey:kMatchNSDate];

    int rv = [date1 compare:date2];
    return rv;

NSMutableArray sortUsingFunction context example.
int SortPlays(id a,  id b, void* context)
    Play* p1=a;
    Play* p2=b;
    if (p1.score     else if (p1.score>p2.score) return NSOrderedAscending;
    return NSOrderedSame;

[validPlays sortUsingFunction:SortPlays context:nil];

End of NSMutableArray sortUsingFunction context example article.