0

I want to order NSMutableArray contain objects according to two of object property one of them has double type second has NSString ?

I tried to use this method but I got exception :

NSString * LASTNAME = @"lastName";
NSString * GRADE = @"grade";

NSSortDescriptor *lastDescriptor =
    [[NSSortDescriptor alloc]
        initWithKey:LASTNAME
          ascending:YES
           selector:@selector(localizedCaseInsensitiveCompare:)];

NSSortDescriptor *firstDescriptor =
    [[NSSortDescriptor alloc]
        initWithKey:GRADE
          ascending:YES
           selector:@selector(localizedCaseInsensitiveCompare:)]];

NSArray * descriptors =
   [NSArray arrayWithObjects:lastDescriptor, firstDescriptor, nil];
NSArray * sortedArray =
   [students sortedArrayUsingDescriptors:descriptors];

@interface Student : NSObject
{
    NSString * firstName;
    NSString * lastName;
    double grade;
}

3 Answers 3

1

NSNumber doesn't respond to localizedCaseInsensitiveCompare:. You want just plain compare: for the number.

6
  • should i make grade NSNumber instead of double I tried compare but I got exception again?
    – kartal
    Commented May 18, 2012 at 4:17
  • @salamonti: Key-Value Coding will return an NSNumber for a double, so that wouldn't be a problem. What is the exact exception you're getting?
    – Chuck
    Commented May 18, 2012 at 4:32
  • you are right and I solved it by remove compare also so it will be NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:GRADE ascending:YES]];
    – kartal
    Commented May 18, 2012 at 4:37
  • Really? That worked? I thought that compare: was the default, so removing compare: shouldn't do anything, should it?
    – rdelmar
    Commented May 18, 2012 at 4:42
  • @rdelmar i didn't see the result yet if it was working write I will add it as right answer
    – kartal
    Commented May 18, 2012 at 5:12
1

Numbers don't have a case, try using compare: for GRADE

After Edit: You didn't say what error you got. Did the code you posted even compile? You have a typo in your firstDescriptor -- one too many "]" at the end of the method. You probably fixed that when you took out the compare: (which shouldn't have fixed anything).

0

Remove localizedCaseInsensitiveCompare

NSSortDescriptor *firstDescriptor =
    [[NSSortDescriptor alloc]
        initWithKey:GRADE
          ascending:YES]];
1
  • This code will not compile -- once again, you have an extra "]" at the end.
    – rdelmar
    Commented May 18, 2012 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.