Friday, May 31, 2013

NSArray sortedArrayUsingDescriptors example in Objective C (iOS).

NSArray sortedArrayUsingDescriptors

Returns a copy of the receiving array sorted as specified by a given array of sort descriptors.

- (NSArray *)sortedArrayUsingDescriptors:(NSArray *)sortDescriptors

An array of NSSortDescriptor objects.

Return Value
A copy of the receiving array sorted as specified by sortDescriptors.

Discussion of [NSArray sortedArrayUsingDescriptors]
The first descriptor specifies the primary key path to be used in sorting the receiving array’s contents. Any subsequent descriptors are used to further refine sorting of objects with duplicate values. See NSSortDescriptor for additional information.

NSArray sortedArrayUsingDescriptors example.
NSSortDescriptor * frequencyDescriptor =
    [[[NSSortDescriptor alloc] initWithKey:FREQUENCY
                                 ascending:YES] autorelease];

id obj;
NSEnumerator * enumerator = [array objectEnumerator];
while ((obj = [enumerator nextObject])) NSLog(@"%@", obj);

NSArray * descriptors =
    [NSArray arrayWithObjects:frequencyDescriptor, nil];
NSArray * sortedArray =
    [array sortedArrayUsingDescriptors:descriptors];

NSLog(@"\nSorted ...");

enumerator = [sortedArray objectEnumerator];
while ((obj = [enumerator nextObject])) NSLog(@"%@", obj);

Example of [NSArray sortedArrayUsingDescriptors].
NSSortDescriptor *country = [[[NSSortDescriptor alloc] initWithKey:@"country" ascending:YES]autorelease];
NSSortDescriptor *city = [[[NSSortDescriptor alloc] initWithKey:@"city" ascending:YES]autorelease];
NSArray *sorted = [bag sortedArrayUsingDescriptors:[NSArray arrayWithObjects: country, city, nil]];

NSArray sortedArrayUsingDescriptors example.
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest"  ascending:YES];
    [stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
    recent = [stories copy];

End of NSArray sortedArrayUsingDescriptors example article.