3

iam trying to sort a object with 2 numbers using the api sortedArrayUsingComparator

array1= [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

    person *p1 = (person*)obj1;
    person *p2 = (person*)obj2;

    if (p1.value>p2.value && p1.age>p2.age)
    {
        return (NSComparisonResult)NSOrderedAscending;
    }
    else
        return (NSComparisonResult)NSOrderedDescending;
}];

i want to make code to sort something like this ,,,,

input : 0  1
        1  2
        0  9
        1  4
        2  3

output: 0  1
        0  9
        1  2
        1  4 
        2  3

2 Answers 2

14
  1. Please don't cast id to person *. The type id is implicitly compatible with any Objective-C object type, so the cast is useless and it only decreases readability.

  2. Also, class names should begin with a capital letter. Better name your class Person, not person.

  3. The actual problem is somewhat similar to lexicographic sorting:


NSArray *sorted = [unsorted sortedArrayUsingComparator:^NSComparisonResult(id lhs, id rhs) {
    Person *p1 = lhs, *p2 = rhs;

    if (p1.value > p2.value) {
        return NSOrderedAscending;
    } else if (p1.value < p2.value) {
        return NSOrderedDescending;
    } else {
        if (p1.age > p2.age)
            return NSOrderedAscending;
        else if (p1.age < p2.age)
            return NSOrderedDescending;
        else
            return NSOrderedSame;
    }
}];
Sign up to request clarification or add additional context in comments.

6 Comments

1. Please don't use the comma operator ever.
2. Using proper parameter types for the block removes need for secondary variables altogether.
@NikolaiRuhe 1. I haven't used the comma operator anywhere. 2. But then the block wouldn't be of a compatible type. (Try it, you will get a compiler error.) I'd prefer that if it was legal. 3. Thanks.
1. OK, wrong term, you can keep your declaration separator. 2. The block would be of compatible type (no compiler warning in current clang when using (Person *lhs, Person *rhs), with -Weverything).
@NikolaiRuhe 1. Thanks! 2. So rather I should try it. (And GCC was wrong then. Would you happen to know if the C rule for compatible function types does not apply to blocks? It seems so...)
|
5

I would recommend sorting with NSSortDescriptors:

NSArray *sortdesc = @[
                      [NSSortDescriptor sortDescriptorWithKey:@"value" ascending:YES],
                      [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]
                     ];
NSLog(@"%@", [array sortedArrayUsingDescriptors:sortdesc]);

Comments

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.