Reputation: 289
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
Upvotes: 3
Views: 7438
Reputation: 57179
I would recommend sorting with NSSortDescriptors:
NSArray *sortdesc = @[
[NSSortDescriptor sortDescriptorWithKey:@"value" ascending:YES],
[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]
];
NSLog(@"%@", [array sortedArrayUsingDescriptors:sortdesc]);
Upvotes: 5
Reputation:
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.
Also, class names should begin with a capital letter. Better name your class Person
, not person
.
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;
}
}];
Upvotes: 14