Friday, May 31, 2013

NSArray sortedArrayUsingFunction context example in Objective C (iOS).


NSArray sortedArrayUsingFunction context

Returns a new array that lists the receiving array’s elements in ascending order as defined by the comparison function comparator.

- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context

Discussion of [NSArray sortedArrayUsingFunction context]
The new array contains references to the receiving array’s elements, not copies of them.

The comparison function is used to compare two elements at a time and 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. Each time the comparison function is called, it’s passed context as its third argument. This allows the comparison to be based on some outside parameter, such as whether character sorting is case-sensitive or case-insensitive.
[NSArray sortedArrayUsingFunction context]
Given anArray (an array of NSNumber objects) and a comparison function of this type:

NSInteger intSort(id num1, id num2, void *context)
{
int v1 = [num1 intValue];
int v2 = [num2 intValue];
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
A sorted version of anArray is created in this way:

NSArray *sortedArray; sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];

NSArray sortedArrayUsingFunction context example.
NSArray *sorted_bookings = [myUnsortedArray sortedArrayUsingFunction:Sort_Bookingdate_Comparer context:self];  

NSInteger Sort_Bookingdate_Comparer(id id1, id id2, void *context)
{
    // Sort Function
    Booking* booking1 = (Booking*)id1; 
    Booking* booking2 = (Booking*)id2; 

    return ([booking1.BOOKING_DATE compare:booking2.BOOKING_DATE]);
}

Example of [NSArray sortedArrayUsingFunction context].
NSInteger personSort(id p1, id p2, void *context)
{
    NSString *name1 = [(MYPersonClass *)p1 firstName];
    NSString *name2 = [(MYPersonClass *)p2 firstName];
    return [name1 compare:name2]
}

NSArray *sortedPerson = [allPeople sortedArrayUsingFunction:personSort context:NULL];

NSArray sortedArrayUsingFunction context example.
NSInteger sortNames(id id1, id id2, void *context)
{
    // Sort Function
    NSString* name1 = (NSString*)id1; 
    NSString* name2 = (NSString*)id2; 

    return ([name1 compare:name2]);
}

int main (int argc, const char * argv[])
{
    NSArray *unsorted = [NSArray arrayWithObjects:@"John", @"Bob", @"Avril", nil];
    NSArray *names = [unsorted sortedArrayUsingFunction:sortNames context:nil];  

    for (NSString* item in names)
    {
        NSLog(@"%@", item);
    }

    return 0;
}

End of NSArray sortedArrayUsingFunction context example article.