问题
I only have a limited experience in using NSSortDescriptor. It was sorting on one key and it worked fine. But here is what I need now, I have a set of pairs of numbers, for example : {(2,3), (44,5), (6,17), (33,7) ……(173,21)} I want to sort the pairs (x,y) according to the value of a given function myfunction(x,y). There is the trivial idea of making triplets (x,y,z) where z would be the computation of myfunction(x,y) and then sort the set of triplets, but this not what I want.
Is there a proper way to use NSSortDescriptor to do what I need?
Thanks for any information.
回答1:
Unless you are using this sort descriptor with Core Data using a SQLite store, you could create a transient attribute on the object where the attribute represented z, the computation of your function. You could then sort on that transient attribute and it would produce the results you want, without storing the z values.
However, if you are using Core Data with a store like SQLite where the entire store contents are not read into memory, you cannot use transient attributes to sort on and you would have to either store your z values actually in the managed objects in order to achieve what you are describing, or read all of your managed objects into an array, and then sort that array of objects on the transient property... which would work OK if you only had a limited number of managed objects, but not so well otherwise.
来源:https://stackoverflow.com/questions/8090397/nssortdescriptor-with-a-function