Question

With this

    NSSortDescriptor *lessonDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lesson" ascending:YES];
[resultArray sortUsingDescriptors:[NSArray arrayWithObject:lessonDescriptor]];

it's sorting the "lesson"-objects to

(
    {
    lesson = 9;
    subject = bg;
},
    {
    lesson = 8;
    subject = bg;
},
    {
    lesson = 11;
    subject = CAE;
},
    {
    lesson = 11;
    subject = CAE;
},
    {
    lesson = 10;
    subject = CAE;
},
    {
    lesson = 10;
    subject = CAE;
},
    {
    lesson = 5;
    subject = Gg;
},
    {
    lesson = 4;
    subject = G;
},
    {
    lesson = 3;
    subject = G;
},
    {
    lesson = 2;
    subject = M;
},
    {
    lesson = 1;
    subject = M;
}

)

as you can see it's not counting correctly.. Can somebody help?

thanks alot

edit:

don't know how to implement the value thing =)

else if ([currentElement isEqualToString:@"lesson"]) 
{ 

    NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSLog(@"trimmed: %@",trimmedString);
    int value = [trimmedString intValue];   ??
    [currentSummary appendString:value];  ??

    [currentSummary appendString:trimmedString]; 
} 
Was it helpful?

Solution

You have to trim the string before converting the 'lesson' into numbers in order for the sort descriptors to work correctly. Otherwise, the sort descriptor sees only string values not numbers. This is how you remove the whitespace and newline characters:

NSString *stringValue = [parsedValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

A call to [stringValue intValue] will get the integer value of the string

int value = [stringValue intValue];

Save this value into the array before calling the sort descriptors on this attribute.

Tell me if it works.

OTHER TIPS

It sorted it just right. After all, every entry is a string, and in a string "10" is before "9" after all...

Now if you wanted to sort it the way you expected to sort it, you either need to hold NSNuumber objects and sort that, or have strings held in normalized form like "08", "09", "10", and then possibly trim off leading 0's from the string later.

[NSSortDescriptor sortDescriptorWithKey:@"self"
                              ascending:YES
                             comparator:^(id obj1, id obj2){
    return [(NSString*)obj1 compare:(NSString*)obj2
                            options:NSNumericSearch];
 }];

sorts a range from 0 - 1000000..... onwards.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top