The second sort descriptor does not make any sense to me. It applies the given comparator
to the score
attribute of the objects to compare. So inside the comparator,
obj1
, obj2
are the score values of the to-be-compared objects.
It seems that you try to get the underlying objects with
[array objectAtIndex:[obj1 integerValue]]
[array objectAtIndex:[obj2 integerValue]]
but that cannot work. So the second sort descriptor should look like
[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO
comparator:^NSComparisonResult(Item *item1, Item *item2) {
// compare item1, item2 ...
}];
But then the next problem arises: How to compare two objects according to priority? Your code does essentially the following:
if ([item2 valueForKey:@"lessImportantItems"] containsObject:item1]) {
return NSOrderedAscending;
} else {
return NSOrderedDescending;
}
But that is not a proper comparator:
- It does not return
NSOrderedSame
if the objects are equal (not "reflexive"), - For two "unrelated objects" it will return
NSOrderedDescending
regardless of the order (not "asymmetric"), - it does not detect if
item1
is only indirectly related toitem2
(not "transitive").
But how to sort "unrelated objects"? There is no unique solution. If both B and C are less important than A, then both A, B, C and A, C, B are valid solutions. What should the comparator return when comparing B and C?
So I think that cannot be achieved with a sort descriptor and you have to choose some other algorithm, e.g. "Topological sorting".