Friday, May 31, 2013

NSArray sortedArrayUsingSelector example in Objective C (iOS).


NSArray sortedArrayUsingSelector

Returns an array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by a given selector.

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator

Parameters
comparator
A selector that identifies the method to use to compare two elements at a time. The method should return NSOrderedAscending if the receiving array is smaller than the argument, NSOrderedDescending if the receiving array is larger than the argument, and NSOrderedSame if they are equal.

Return Value of [NSArray sortedArrayUsingSelector]
An array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by the selector comparator.

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

The comparator message is sent to each object in the array and has as its single argument another object in the array.

For example, an array of NSString objects can be sorted by using the caseInsensitiveCompare: method declared in the NSString class. Assuming anArray exists, a sorted version of the array can be created in this way:

NSArray *sortedArray =
[anArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

NSArray sortedArrayUsingSelector example.
NSArray *sortedValues = [[yourDictionary allValues] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSMutableDictionary *orderedDictionary=[[NSMutableDictionary alloc]init];
for(NSString *valor in sortedValues){
    for(NSString *clave in [yourDictionary allKeys]){
        if ([valor isEqualToString:[yourDictionary valueForKey:clave]]) {
            [orderedDictionary setValue:valor forKey:clave];
        }
    }
}

Example of [NSArray sortedArrayUsingSelector].
NSArray *keys = [dict allKeys];
NSArray *sKeys = [keys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
NSMutableArray *sValues = [[[NSMutableArray alloc] init] autorelease];

for(id k in sKeys) {
    id val = [dict objectForKey:k];
    [sValues addObject:val];
}

NSArray sortedArrayUsingSelector example.
  NSArray *arraysort=[[NSArray alloc] initWithObjects:@"z",@"v",@"a",@"g",@"b", nil];
 NSArray   *sortedArray = [arraysort sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    for (NSString *str in sortedArray) {
        NSLog(@"string %@ ",str);
    }
    NSLog(@"sortedarrayelements %d",[sortedArray count]);

End of NSArray sortedArrayUsingSelector example article.