views:

75

answers:

2

Hello I have an array of persons, and i am trying to sort them by age using a sort descriptor. The age field in a patient is a string so when calling:

ageSorter = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
[personList sortUsingDescriptors:[NSArray arrayWithObject:ageSorter]];

It sorts them but 100 appears first because its is not using numericSearch in the compare options.

Is there a ways i can still sort with descriptor but maybe using a selector to change how to compare the strings?

A: 

You could create a category on NSString that adds a method numericCompare: and which calls [self compare:otherString options:NSNumericSearch]. Another option is to convert the age field into a NSNumber instead of a NSString. Yet another option involves a NSComparator block and sortUsingComparator.

lucius
How would i be able to use the NSComparator block?Because don't i still need to get the key from the array?
Matt
The `sortUsingComparator:` method is only available on iOS 4.0 and I don't really know enough about blocks to write the code off the top of my head, so you might want to use the sort using the function option.
lucius
+1  A: 

The finderSortWithLocale method (both these are taken from apple api):

int finderSortWithLocale(Person *person1, Person *person2, void *locale)
{
    static NSStringCompareOptions comparisonOptions = NSNumericSearch;

    NSRange string1Range = NSMakeRange(0, [string1 length]);
    NSString *age1 = person1.age;
    NSString *age2 = person2.age;
    return [age1 compare:age2
                    options:comparisonOptions
                    range:string1Range
                    locale:(NSLocale *)locale];
}

How to call this method (edited: call the function on array of Persons):

    NSArray *sortedArray = [personList sortedArrayUsingFunction:finderSortWithLocale
                                         context:[NSLocale currentLocale]];
Jesse Naugher
but how would i call on person age. Cause i need to get the age key from my persons object
Matt
editing the code to do this. basically you can edit the finderSort: method to do this as long as your using it only on your person object.
Jesse Naugher
OO ok i see what your saying. Where do i place the finderSortWithLocale? in the patient object class?
Matt
you can place it in the class doing the sorting, or if its used frequently you could put it in your singleton if you wanted, those would be the simplest ways imo. then youd call simpleton.finderSortWithLocale
Jesse Naugher
one note: if this code doesnt work, you may have to use id as the param for person1 and person2 and then typecast it to a person inside the function and then gets it age.
Jesse Naugher